PageSourceSearch

https://retrobridge.io/static/js/560.a3b61ff6.chunk.js

js retrobridge.io collected 2026-10-07 17:36:21 UTC 352,090 bytes, 3 lines download raw bytes

1/*! For license information please see 560.a3b61ff6.chunk.js.LICENSE.txt */
2"use strict";(self.webpackChunkretrobridge=self.webpackChunkretrobridge||[]).push([[560],{60560:(e,t,i)=>{i.d(t,{getStarknetWindowObject:()=>tf});var s,r=i(14902),n=i(47747),o=i(63059),a=(i(92472),i(28398)),c=Object.defineProperty,h=(e,t,i)=>(((e,t,i)=>{t in e?c(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i})(e,"symbol"!=typeof t?t+"":t,i),i),l={exports:{}},u="object"==typeof Reflect?Reflect:null,d=u&&"function"==typeof u.apply?u.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};s=u&&"function"==typeof u.ownKeys?u.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var p=Number.isNaN||function(e){return e!==e};function g(){g.init.call(this)}l.exports=g,l.exports.once=function(e,t){return new Promise((function(i,s){function r(i){e.removeListener(t,n),s(i)}function n(){"function"==typeof e.removeListener&&e.removeListener("error",r),i([].slice.call(arguments))}I(e,t,n,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&I(e,"error",t,i)}(e,r,{once:!0})}))},g.EventEmitter=g,g.prototype._events=void 0,g.prototype._eventsCount=0,g.prototype._maxListeners=void 0;var f=10;function y(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function m(e){return void 0===e._maxListeners?g.defaultMaxListeners:e._maxListeners}function w(e,t,i,s){var r,n,o;if(y(i),void 0===(n=e._events)?(n=e._events=Object.create(null),e._eventsCount=0):(void 0!==n.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),n=e._events),o=n[t]),void 0===o)o=n[t]=i,++e._eventsCount;else if("function"==typeof o?o=n[t]=s?[i,o]:[o,i]:s?o.unshift(i):o.push(i),(r=m(e))>0&&o.length>r&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=e,a.type=t,a.count=o.length,function(e){console&&console.warn&&console.warn(e)}(a)}return e}function v(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function b(e,t,i){var s={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},r=v.bind(s);return r.listener=i,s.wrapFn=r,r}function _(e,t,i){var s=e._events;if(void 0===s)return[];var r=s[t];return void 0===r?[]:"function"==typeof r?i?[r.listener||r]:[r]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(r):S(r,r.length)}function E(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function S(e,t){for(var i=new Array(t),s=0;s<t;++s)i[s]=e[s];return i}function I(e,t,i,s){if("function"==typeof e.on)s.once?e.once(t,i):e.on(t,i);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function r(n){s.once&&e.removeEventListener(t,r),i(n)}))}}Object.defineProperty(g,"defaultMaxListeners",{enumerable:!0,get:function(){return f},set:function(e){if("number"!=typeof e||e<0||p(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");f=e}}),g.init=function(){(void 0===this._events||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},g.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||p(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},g.prototype.getMaxListeners=function(){return m(this)},g.prototype.emit=function(e){for(var t=[],i=1;i<arguments.length;i++)t.push(arguments[i]);var s="error"===e,r=this._events;if(void 0!==r)s=s&&void 0===r.error;else if(!s)return!1;if(s){var n;if(t.length>0&&(n=t[0]),n instanceof Error)throw n;var o=new Error("Unhandled error."+(n?" ("+n.message+")":""));throw o.context=n,o}var a=r[e];if(void 0===a)return!1;if("function"==typeof a)d(a,this,t);else{var c=a.length,h=S(a,c);for(i=0;i<c;++i)d(h[i],this,t)}return!0},g.prototype.addListener=function(e,t){return w(this,e,t,!1)},g.prototype.on=g.prototype.addListener,g.prototype.prependListener=function(e,t){return w(this,e,t,!0)},g.prototype.once=function(e,t){return y(t),this.on(e,b(this,e,t)),this},g.prototype.prependOnceListener=function(e,t){return y(t),this.prependListener(e,b(this,e,t)),this},g.prototype.removeListener=function(e,t){var i,s,r,n,o;if(y(t),void 0===(s=this._events))return this;if(void 0===(i=s[e]))return this;if(i===t||i.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete s[e],s.removeListener&&this.emit
2("removeListener",e,i.listener||t));else if("function"!=typeof i){for(r=-1,n=i.length-1;n>=0;n--)if(i[n]===t||i[n].listener===t){o=i[n].listener,r=n;break}if(r<0)return this;0===r?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,r),1===i.length&&(s[e]=i[0]),void 0!==s.removeListener&&this.emit("removeListener",e,o||t)}return this},g.prototype.off=g.prototype.removeListener,g.prototype.removeAllListeners=function(e){var t,i,s;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var r,n=Object.keys(i);for(s=0;s<n.length;++s)"removeListener"!==(r=n[s])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(s=t.length-1;s>=0;s--)this.removeListener(e,t[s]);return this},g.prototype.listeners=function(e){return _(this,e,!0)},g.prototype.rawListeners=function(e){return _(this,e,!1)},g.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):E.call(e,t)},g.prototype.listenerCount=E,g.prototype.eventNames=function(){return this._eventsCount>0?s(this._events):[]};var O=l.exports;const N=(0,r.e)(O);var P={},R={exports:{}};!function(e){var t,i,s,n,o,a,c,h,l,u,d,p,g,f,y,m,w,v,b,_,E,S,I;!function(O){var N="object"==typeof r.c?r.c:"object"==typeof self?self:"object"==typeof this?this:{};function P(e,t){return e!==N&&("function"==typeof Object.create?Object.defineProperty(e,"__esModule",{value:!0}):e.__esModule=!0),function(i,s){return e[i]=t?t(i,s):s}}!function(e){var r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])};t=function(e,t){function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)},i=Object.assign||function(e){for(var t,i=1,s=arguments.length;i<s;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},s=function(e,t){var i={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(i[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(s=Object.getOwnPropertySymbols(e);r<s.length;r++)t.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(e,s[r])&&(i[s[r]]=e[s[r]])}return i},n=function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},o=function(e,t){return function(i,s){t(i,s,e)}},a=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},c=function(e,t,i,s){function r(e){return e instanceof i?e:new i((function(t){t(e)}))}return new(i||(i=Promise))((function(i,n){function o(e){try{c(s.next(e))}catch(t){n(t)}}function a(e){try{c(s.throw(e))}catch(t){n(t)}}function c(e){e.done?i(e.value):r(e.value).then(o,a)}c((s=s.apply(e,t||[])).next())}))},h=function(e,t){var i,s,r,n,o={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return n={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(n[Symbol.iterator]=function(){return this}),n;function a(e){return function(t){return c([e,t])}}function c(n){if(i)throw new TypeError("Generator is already executing.");for(;o;)try{if(i=1,s&&(r=2&n[0]?s.return:n[0]?s.throw||((r=s.return)&&r.call(s),0):s.next)&&!(r=r.call(s,n[1])).done)return r;switch(s=0,r&&(n=[2&n[0],r.value]),n[0]){case 0:case 1:r=n;break;case 4:return o.label++,{value:n[1],done:!1};case 5:o.label++,s=n[1],n=[0];continue;case 7:n=o.ops.pop(),o.trys.pop();continue;default:if(!(r=(r=o.trys).length>0&&r[r.length-1])&&(6===n[0]||2===n[0])){o=0;continue}if(3===n[0]&&(!r||n[1]>r[0]&&n[1]<r[3])){o.label=n[1];break}if(6===n[0]&&o.label<r[1]){o.label=r[1],r=n;break}if(r&&o.label<r[2]){o.label=r[2],o.ops.push(n);break}r[2]&&o.ops.pop(),o.trys.pop();continue}n=t.call(e,o)}catch(a){n=[6,a],s=0}finally{i=r=0}if(5&n[0])throw n[1];return{value:n[0]?n[1]:void 0,done:!0}}},I=function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]},l=function(e,t){for(var i in e)"default"!==i&&!t.hasOwnProperty(i)&&(t[i]=e[i])},u=function(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],s=0;if(i)return i.call(e);
vendor: 2,964 bytes, line 2
2if(e&&"number"==typeof e.length)return{next:function(){return e&&s>=e.length&&(e=void 0),{value:e&&e[s++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},d=function(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var s,r,n=i.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(a){r={error:a}}finally{try{s&&!s.done&&(i=n.return)&&i.call(n)}finally{if(r)throw r.error}}return o},p=function(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(d(arguments[t]));return e},g=function(){for(var e=0,t=0,i=arguments.length;t<i;t++)e+=arguments[t].length;var s=Array(e),r=0;for(t=0;t<i;t++)for(var n=arguments[t],o=0,a=n.length;o<a;o++,r++)s[r]=n[o];return s},f=function(e){return this instanceof f?(this.v=e,this):new f(e)},y=function(e,t,i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s,r=i.apply(e,t||[]),n=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(e){r[e]&&(s[e]=function(t){return new Promise((function(i,s){n.push([e,t,i,s])>1||a(e,t)}))})}function a(e,t){try{c(r[e](t))}catch(i){u(n[0][3],i)}}function c(e){e.value instanceof f?Promise.resolve(e.value.v).then(h,l):u(n[0][2],e)}function h(e){a("next",e)}function l(e){a("throw",e)}function u(e,t){e(t),n.shift(),n.length&&a(n[0][0],n[0][1])}},m=function(e){var t,i;return t={},s("next"),s("throw",(function(e){throw e})),s("return"),t[Symbol.iterator]=function(){return this},t;function s(s,r){t[s]=e[s]?function(t){return(i=!i)?{value:f(e[s](t)),done:"return"===s}:r?r(t):t}:r}},w=function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,i=e[Symbol.asyncIterator];return i?i.call(e):(e=u(e),t={},s("next"),s("throw"),s("return"),t[Symbol.asyncIterator]=function(){return this},t);function s(i){t[i]=e[i]&&function(t){return new Promise((function(s,n){r(s,n,(t=e[i](t)).done,t.value)}))}}function r(e,t,i,s){Promise.resolve(s).then((function(t){e({value:t,done:i})}),t)}},v=function(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e},b=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)Object.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t.default=e,t},_=function(e){return e&&e.__esModule?e:{default:e}},E=function(e,t){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return t.get(e)},S=function(e,t,i){if(!t.has(e))throw new TypeError("attempted to set private field on non-instance");return t.set(e,i),i},e("__extends",t),e("__assign",i),e("__rest",s),e("__decorate",n),e("__param",o),e("__metadata",a),e("__awaiter",c),e("__generator",h),e("__exportStar",l),e("__createBinding",I),e("__values",u),e("__read",d),e("__spread",p),e("__spreadArrays",g),e("__await",f),e("__asyncGenerator",y),e("__asyncDelegator",m),e("__asyncValues",w),e("__makeTemplateOb
2ject",v),e("__importStar",b),e("__importDefault",_),e("__classPrivateFieldGet",E),e("__classPrivateFieldSet",S)}(P(N,P(e.exports)))}()}(R);var T=R.exports,x={};Object.defineProperty(x,"__esModule",{value:!0}),x.safeJsonParse=function(e){if("string"!=typeof e)throw new Error("Cannot safe json parse value of type "+typeof e);try{return JSON.parse(e)}catch{return e}},x.safeJsonStringify=function(e){return"string"==typeof e?e:JSON.stringify(e,((e,t)=>typeof t>"u"?null:t))};var A,C={exports:{}};var L,U={},M={};var D,j,k={};Object.defineProperty(P,"__esModule",{value:!0}),P.KeyValueStorage=void 0;const z=T,q=x,$=z.__importDefault((A||(A=1,function(){let e;function t(){}e=t,e.prototype.getItem=function(e){return this.hasOwnProperty(e)?String(this[e]):null},e.prototype.setItem=function(e,t){this[e]=String(t)},e.prototype.removeItem=function(e){delete this[e]},e.prototype.clear=function(){const e=this;Object.keys(e).forEach((function(t){e[t]=void 0,delete e[t]}))},e.prototype.key=function(e){return e=e||0,Object.keys(this)[e]},e.prototype.__defineGetter__("length",(function(){return Object.keys(this).length})),typeof r.c<"u"&&r.c.localStorage?C.exports=r.c.localStorage:typeof window<"u"&&window.localStorage?C.exports=window.localStorage:C.exports=new t}()),C.exports)),K=(j||(j=1,function(e){Object.defineProperty(e,"__esModule",{value:!0});const t=T;t.__exportStar((L||(L=1,Object.defineProperty(M,"__esModule",{value:!0}),M.IKeyValueStorage=void 0,M.IKeyValueStorage=class{}),M),e),t.__exportStar(function(){if(D)return k;D=1,Object.defineProperty(k,"__esModule",{value:!0}),k.parseEntry=void 0;const e=x;return k.parseEntry=function(t){var i;return[t[0],e.safeJsonParse(null!==(i=t[1])&&void 0!==i?i:"")]},k}(),e)}(U)),U);class V{constructor(){this.localStorage=$.default}getKeys(){return z.__awaiter(this,void 0,void 0,(function*(){return Object.keys(this.localStorage)}))}getEntries(){return z.__awaiter(this,void 0,void 0,(function*(){return Object.entries(this.localStorage).map(K.parseEntry)}))}getItem(e){return z.__awaiter(this,void 0,void 0,(function*(){const t=this.localStorage.getItem(e);if(null!==t)return q.safeJsonParse(t)}))}setItem(e,t){return z.__awaiter(this,void 0,void 0,(function*(){this.localStorage.setItem(e,q.safeJsonStringify(t))}))}removeItem(e){return z.__awaiter(this,void 0,void 0,(function*(){this.localStorage.removeItem(e)}))}}P.KeyValueStorage=V;var H,F=P.default=V,B={},G={},W={},Y={},J={};var Q,X={},Z={},ee={};var te,ie,se,re,ne={};function oe(){return ie||(ie=1,function(e){Object.defineProperty(e,"__esModule",{value:!0});const t=T;
2t.__exportStar((Q||(Q=1,Object.defineProperty(ee,"__esModule",{value:!0}),ee.ONE_THOUSAND=ee.ONE_HUNDRED=void 0,ee.ONE_HUNDRED=100,ee.ONE_THOUSAND=1e3),ee),e),t.__exportStar(function(){return te||(te=1,e=ne,Object.defineProperty(e,"__esModule",{value:!0}),e.ONE_YEAR=e.FOUR_WEEKS=e.THREE_WEEKS=e.TWO_WEEKS=e.ONE_WEEK=e.THIRTY_DAYS=e.SEVEN_DAYS=e.FIVE_DAYS=e.THREE_DAYS=e.ONE_DAY=e.TWENTY_FOUR_HOURS=e.TWELVE_HOURS=e.SIX_HOURS=e.THREE_HOURS=e.ONE_HOUR=e.SIXTY_MINUTES=e.THIRTY_MINUTES=e.TEN_MINUTES=e.FIVE_MINUTES=e.ONE_MINUTE=e.SIXTY_SECONDS=e.THIRTY_SECONDS=e.TEN_SECONDS=e.FIVE_SECONDS=e.ONE_SECOND=void 0,e.ONE_SECOND=1,e.FIVE_SECONDS=5,e.TEN_SECONDS=10,e.THIRTY_SECONDS=30,e.SIXTY_SECONDS=60,e.ONE_MINUTE=e.SIXTY_SECONDS,e.FIVE_MINUTES=5*e.ONE_MINUTE,e.TEN_MINUTES=10*e.ONE_MINUTE,e.THIRTY_MINUTES=30*e.ONE_MINUTE,e.SIXTY_MINUTES=60*e.ONE_MINUTE,e.ONE_HOUR=e.SIXTY_MINUTES,e.THREE_HOURS=3*e.ONE_HOUR,e.SIX_HOURS=6*e.ONE_HOUR,e.TWELVE_HOURS=12*e.ONE_HOUR,e.TWENTY_FOUR_HOURS=24*e.ONE_HOUR,e.ONE_DAY=e.TWENTY_FOUR_HOURS,e.THREE_DAYS=3*e.ONE_DAY,e.FIVE_DAYS=5*e.ONE_DAY,e.SEVEN_DAYS=7*e.ONE_DAY,e.THIRTY_DAYS=30*e.ONE_DAY,e.ONE_WEEK=e.SEVEN_DAYS,e.TWO_WEEKS=2*e.ONE_WEEK,e.THREE_WEEKS=3*e.ONE_WEEK,e.FOUR_WEEKS=4*e.ONE_WEEK,e.ONE_YEAR=365*e.ONE_DAY),ne;var e}(),e)}(Z)),Z}function ae(){return re||(re=1,function(e){Object.defineProperty(e,"__esModule",{value:!0});const t=T;t.__exportStar((H||(H=1,Object.defineProperty(J,"__esModule",{value:!0}),J.delay=void 0,J.delay=function(e){return new Promise((t=>{setTimeout((()=>{t(!0)}),e)}))}),J),e),t.__exportStar(function(){if(se)return X;se=1,Object.defineProperty(X,"__esModule",{value:!0}),X.fromMiliseconds=X.toMiliseconds=void 0;const e=oe();return X.toMiliseconds=function(t){return t*e.ONE_THOUSAND},X.fromMiliseconds=function(t){return Math.floor(t/e.ONE_THOUSAND)},X}(),e)}(Y)),Y}var ce,he={};var le,ue,de={},pe={};function ge(){return ue||(ue=1,e=de,Object.defineProperty(e,"__esModule",{value:!0}),T.__exportStar((le||(le=1,Object.defineProperty(pe,"__esModule",{value:!0}),pe.IWatch=void 0,pe.IWatch=class{}),pe),e)),de;var e}!function(e){Object.defineProperty(e,"__esModule",{value:!0});const t=T;t.__exportStar(ae(),e),t.__exportStar(function(){if(ce)return he;ce=1,Object.defineProperty(he,"__esModule",{value:!0}),he.Watch=void 0;class e{constructor(){this.timestamps=new Map}start(e){if(this.timestamps.has(e))throw new Error(`Watch already started for label: ${e}`);this.timestamps.set(e,{started:Date.now()})}stop(e){const t=this.get(e);if(typeof t.elapsed<"u")throw new Error(`Watch already stopped for label: ${e}`);const i=Date.now()-t.started;this.timestamps.set(e,{started:t.started,elapsed:i})}get(e){const t=this.timestamps.get(e);if(typeof t>"u")throw new Error(`No timestamp found for label: ${e}`);return t}elapsed(e){const t=this.get(e);return t.elapsed||Date.now()-t.started}}return he.Watch=e,he.default=e,he}(),e),t.__exportStar(ge(),e),t.__exportStar(oe(),e)}(W);var fe={},ye={};let me=class{};const we=Object.freeze(Object.defineProperty({__proto__:null,IEvents:me},Symbol.toStringTag,{value:"Module"})),ve=(0,r.g)(we);var be,_e;function Ee(){return _e||(_e=1,e=fe,Object.defineProperty(e,"__esModule",{value:!0}),T.__exportStar(function(){if(be)return ye;be=1,Object.defineProperty(ye,"__esModule",{value:!0}),ye.IHeartBeat=void 0;const e=ve;class t extends e.IEvents{constructor(e){super()}}return ye.IHeartBeat=t,ye}(),e)),fe;var e}var Se,Ie,Oe,Ne={},Pe={};function Re(){return Ie||(Ie=1,e=Ne,Object.defineProperty(e,"__esModule",{value:!0}),T.__exportStar(function(){if(Se)return Pe;Se=1,Object.defineProperty(Pe,"__esModule",{value:!0}),Pe.HEARTBEAT_EVENTS=Pe.HEARTBEAT_INTERVAL=void 0;const e=W;return Pe.HEARTBEAT_INTERVAL=e.FIVE_SECONDS,Pe.HEARTBEAT_EVENTS={pulse:"heartbeat_pulse"},Pe}(),e)),Ne;var e}!function(e){Object.defineProperty(e,"__esModule",{value:!0});const t=T;t.__exportStar(function(){if(Oe)return G;Oe=1,Object.defineProperty(G,"__esModule",{value:!0}),G.HeartBeat=void 0;const e=T,t=O,i=W,s=Ee(),r=Re();class n extends s.IHeartBeat{constructor(e){super(e),this.events=new t.EventEmitter,this.interval=r.HEARTBEAT_INTERVAL,this.interval=(null===e||void 0===e?void 0:e.interval)||r.HEARTBEAT_INTERVAL}static init(t){return e.__awaiter(this,void 0,void 0,(function*(){const e=new n(t);return yield e.init(),e}))}init(){return e.__awaiter(this,void 0,void 0,(function*(){yield 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)}initialize(){return e.__awaiter(this,void 0,void 0,(function*(){this.intervalRef=setInterval((()=>this.pulse()),i.toMiliseconds(this.interval))}))}pulse(){this.events.emit(r.HEARTBEAT_EVENTS.pulse)}}return G.HeartBeat=n,G}(),e),t.__exportStar(Ee(),e),t.__exportStar(Re(),e)}(B);var Te,xe,Ae,Ce,Le={};function Ue(){if(Ce)return Ae;Ce=1;const e=function(){if(xe)return Te;function e(e){try{return JSON.stringify(e)}catch{return'"[Circular]"'}}return xe=1,Te=function(t,i,s){var r=s&&s.stringify||e;if("object"==typeof t&&null!==t){var n=i.length+1;if(1===n)return t;var o=new Array(n);o[0]=r(t);for(var a=1;a<n;a++)o[a]=r(i[a]);return o.join(" ")}if("string"!=typeof t)return t;var c=i.length;if(0===c)return t;for(var h="",l=0,u=-1,d=t&&t.length||0,p=0;p<d;){if(37===t.charCodeAt(p)&&p+1<d){switch(u=u>-1?u:0,t.charCodeAt(p+1)){case 100:case 102:if(l>=c||null==i[l])break;u<p&&(h+=t.slice(u,p)),h+=Number(i[l]),u=p+2,p++;break;case 105:if(l>=c||null==i[l])break;u<p&&(h+=t.slice(u,p)),h+=Math.floor(Number(i[l])),u=p+2,p++;break;case 79:case 111:case 106:if(l>=c||void 0===i[l])break;u<p&&(h+=t.slice(u,p));var g=typeof i[l];if("string"===g){h+="'"+i[l]+"'",u=p+2,p++;break}if("function"===g){h+=i[l].name||"<anonymous>",u=p+2,p++;break}h+=r(i[l]),u=p+2,p++;break;case 115:if(l>=c)break;u<p&&(h+=t.slice(u,p)),h+=String(i[l]),u=p+2,p++;break;case 37:u<p&&(h+=t.slice(u,p)),h+="%",u=p+2,p++,l--}++l}++p}return-1===u?t:(u<d&&(h+=t.slice(u)),h)}}();Ae=s;const t=function(){function e(e){return typeof e<"u"&&e}try{return typeof globalThis<"u"||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch{return e(self)||e(window)||e(this)||{}}}().console||{},i={mapHttpRequest:h,mapHttpResponse:h,wrapRequestSerializer:l,wrapResponseSerializer:l,wrapErrorSerializer:l,req:h,res:h,err:function(e){const t={type:e.constructor.name,msg:e.message,stack:e.stack};for(const i in e)void 0===t[i]&&(t[i]=e[i]);return t}};function s(e){(e=e||{}).browser=e.browser||{};const i=e.browser.transmit;if(i&&"function"!=typeof i.send)throw Error("pino: transmit option must have a send function");const h=e.browser.write||t;e.browser.write&&(e.browser.asObject=!0);const l=e.serializers||{},d=function(e,t){return Array.isArray(e)?e.filter((function(e){return"!stdSerializers.err"!==e})):!0===e&&Object.keys(t)}(e.browser.serialize,l);let p=e.browser.serialize;Array.isArray(e.browser.serialize)&&e.browser.serialize.indexOf("!stdSerializers.err")>-1&&(p=!1);"function"==typeof h&&(h.error=h.fatal=h.warn=h.info=h.debug=h.trace=h),!1===e.enabled&&(e.level="silent");const g=e.level||"info",f=Object.create(h);f.log||(f.log=u),Object.defineProperty(f,"levelVal",{get:function(){return"silent"===this.level?1/0:this.levels.values[this.level]}}),Object.defineProperty(f,"level",{get:function(){return this._level},set:function(e){if("silent"!==e&&!this.levels.values[e])throw Error("unknown level "+e);this._level=e,r(y,f,"error","log"),r(y,f,"fatal","error"),r(y,f,"warn","error"),r(y,f,"info","log"),r(y,f,"debug","log"),r(y,f,"trace","log")}});const y={transmit:i,serialize:d,asObject:e.browser.asObject,levels:["error","fatal","warn","info","debug","trace"],timestamp:c(e)};return f.levels=s.levels,f.level=g,f.setMaxListeners=f.getMaxListeners=f.emit=f.addListener=f.on=f.prependListener=f.once=f.prepe
2ndOnceListener=f.removeListener=f.removeAllListeners=f.listeners=f.listenerCount=f.eventNames=f.write=f.flush=u,f.serializers=l,f._serialize=d,f._stdErrSerialize=p,f.child=function(t,s){if(!t)throw new Error("missing bindings for child Pino");s=s||{},d&&t.serializers&&(s.serializers=t.serializers);const r=s.serializers;if(d&&r){var c=Object.assign({},l,r),h=!0===e.browser.serialize?Object.keys(c):d;delete t.serializers,n([t],h,c,this._stdErrSerialize)}function u(e){this._childLevel=1+(0|e._childLevel),this.error=o(e,t,"error"),this.fatal=o(e,t,"fatal"),this.warn=o(e,t,"warn"),this.info=o(e,t,"info"),this.debug=o(e,t,"debug"),this.trace=o(e,t,"trace"),c&&(this.serializers=c,this._serialize=h),i&&(this._logEvent=a([].concat(e._logEvent.bindings,t)))}return u.prototype=this,new u(this)},i&&(f._logEvent=a()),f}function r(i,r,o,c){const h=Object.getPrototypeOf(r);r[o]=r.levelVal>r.levels.values[o]?u:h[o]?h[o]:t[o]||t[c]||u,function(i,r,o){!i.transmit&&r[o]===u||(r[o]=function(c){return function(){const h=i.timestamp(),l=new Array(arguments.length),u=Object.getPrototypeOf&&Object.getPrototypeOf(this)===t?t:this;for(var d=0;d<l.length;d++)l[d]=arguments[d];if(i.serialize&&!i.asObject&&n(l,this._serialize,this.serializers,this._stdErrSerialize),i.asObject?c.call(u,function(t,i,r,o){t._serialize&&n(r,t._serialize,t.serializers,t._stdErrSerialize);const a=r.slice();let c=a[0];const h={};o&&(h.time=o),h.level=s.levels.values[i];let l=1+(0|t._childLevel);if(l<1&&(l=1),null!==c&&"object"==typeof c){for(;l--&&"object"==typeof a[0];)Object.assign(h,a.shift());c=a.length?e(a.shift(),a):void 0}else"string"==typeof c&&(c=e(a.shift(),a));return void 0!==c&&(h.msg=c),h}(this,o,l,h)):c.apply(u,l),i.transmit){const e=i.transmit.level||r.level,t=s.levels.values[e],c=s.levels.values[o];if(c<t)return;!function(e,t,i){const s=t.send,r=t.ts,o=t.methodLevel,c=t.methodValue,h=t.val,l=e._logEvent.bindings;n(i,e._serialize||Object.keys(e.serializers),e.serializers,void 0===e._stdErrSerialize||e._stdErrSerialize),e._logEvent.ts=r,e._logEvent.messages=i.filter((function(e){return-1===l.indexOf(e)})),e._logEvent.level.label=o,e._logEvent.level.value=c,s(o,e._logEvent,h),e._logEvent=a(l)}(this,{ts:h,methodLevel:o,methodValue:c,transmitLevel:e,transmitValue:s.levels.values[i.transmit.level||r.level],send:i.transmit.send,val:r.levelVal},l)}}}(r[o]))}(i,r,o)}function n(e,t,i,r){for(const n in e)if(r&&e[n]instanceof Error)e[n]=s.stdSerializers.err(e[n]);else if("object"==typeof e[n]&&!Array.isArray(e[n]))for(const s in e[n])t&&t.indexOf(s)>-1&&s in i&&(e[n][s]=i[s](e[n][s]))}function o(e,t,i){return function(){const s=new Array(1+arguments.length);s[0]=t;for(var r=1;r<s.length;r++)s[r]=arguments[r-1];return e[i].apply(this,s)}}function a(e){return{ts:0,messages:[],bindings:e||[],level:{label:"",value:0}}}function c(e){return"function"==typeof e.timestamp?e.timestamp:!1===e.timestamp?d:p}function h(){return{}}function l(e){return e}function u(){}function d(){return!1}function p(){return Date.now()}return 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=i,s.stdTimeFunctions=Object.assign({},{nullTime:d,epochTime:p,unixTime:function(){return Math.round(Date.now()/1e3)},isoTime:function(){return new Date(Date.now()).toISOString()}}),Ae}var Me,De={};function je(){return Me||(Me=1,Object.defineProperty(De,"__esModule",{value:!0}),De.PINO_CUSTOM_CONTEXT_KEY=De.PINO_LOGGER_DEFAULTS=void 0,De.PINO_LOGGER_DEFAULTS={level:"info"},De.PINO_CUSTOM_CONTEXT_KEY="custom_context"),De}var ke,ze={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.pino=void 0;const t=T,i=t.__importDefault(Ue());Object.defineProperty(e,"pino",{enumerable:!0,get:function(){return i.default}}),t.__exportStar(je(),e),t.__exportStar(function(){if(ke)return ze;ke=1,Object.defineProperty(ze,"__esModule",{value:!0}),ze.generateChildLogger=ze.formatChildLoggerContext=ze.getLoggerContext=ze.setBrowserLoggerContext=ze.getBrowserLoggerContext=ze.getDefaultLoggerOptions=void 0;const e=je();function t(t){return t[arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.PINO_CUSTOM_CONTEXT_KEY]||""}function i(t,i){return t[arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.PINO_CUSTOM_CONTEXT_KEY]=i,t}function s(i){let s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.PINO_CUSTOM_CONTEXT_KEY,r="";return r=typeof i.bindings>"u"?t(i,s):i.bindings().context||"",r}function r(t,i){const r=s(t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.PINO_CUSTOM_CONTEXT_KEY);return r.trim()?`${r}/${i}`:i}return ze.getDefaultLoggerOptions=function(t){return Object.assign(Object.assign({},t),{level:(null===t||void 0===t?void 0:t.level)||e.PINO_LOGGER_DEFAULTS.level})},ze.getBrowserLoggerContext=t,ze.setBrowserLoggerContext=i,ze.getLoggerContext=s,ze.formatChildLoggerContext=r,ze.generateChildLogger=function(t,s){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.PINO_CUSTOM_CONTEXT_KEY;const o=r(t,s,n);return i(t.child({context:o}),o,n)},ze}(),e)}(Le);let qe=class extends me{constructor(e){super(),this.opts=e,this.protocol="wc",this.version=2}},$e=class extends me{constructor(e,t){super(),this.core=e,this.logger=t,this.records=new Map}},Ke=class{constructor(e,t){this.logger=e,this.core=t}},Ve=class extends me{constructor(e,t){super(),this.relayer=e,this.logger=t}}
2,He=class extends me{constructor(e){super()}},Fe=class{constructor(e,t,i,s){this.core=e,this.logger=t,this.name=i}},Be=class extends me{constructor(e,t){super(),this.relayer=e,this.logger=t}},Ge=class extends me{constructor(e,t){super(),this.core=e,this.logger=t}},We=class{constructor(e,t){this.projectId=e,this.logger=t}},Ye=class{constructor(e){this.opts=e,this.protocol="wc",this.version=2}},Je=class{constructor(e){this.client=e}};const Qe=e=>JSON.stringify(e,((e,t)=>"bigint"==typeof t?t.toString()+"n":t));function Xe(e){if("string"!=typeof e)throw new Error("Cannot safe json parse value of type "+typeof e);try{return(e=>{const t=e.replace(/([\[:])?(\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,'$1"$2n"$3');return JSON.parse(t,((e,t)=>"string"==typeof t&&t.match(/^\d+n$/)?BigInt(t.substring(0,t.length-1)):t))})(e)}catch{return e}}function Ze(e){return"string"==typeof e?e:Qe(e)||""}var et={},tt={},it={},st={};Object.defineProperty(st,"__esModule",{value:!0}),st.BrowserRandomSource=void 0;st.BrowserRandomSource=class{constructor(){this.isAvailable=!1,this.isInstantiated=!1;const e=typeof self<"u"?self.crypto||self.msCrypto:null;e&&void 0!==e.getRandomValues&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Browser random byte generator is not available.");const t=new Uint8Array(e);for(let i=0;i<t.length;i+=65536)this._crypto.getRandomValues(t.subarray(i,i+Math.min(t.length-i,65536)));return t}};var rt={},nt={};Object.defineProperty(nt,"__esModule",{value:!0}),nt.wipe=function(e){for(var t=0;t<e.length;t++)e[t]=0;return e};const ot=Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})),at=(0,r.g)(ot);Object.defineProperty(rt,"__esModule",{value:!0}),rt.NodeRandomSource=void 0;const ct=nt;rt.NodeRandomSource=class{constructor(){this.isAvailable=!1,this.isInstantiated=!1;{const e=at;e&&e.randomBytes&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Node.js random byte generator is not available.");let t=this._crypto.randomBytes(e);if(t.length!==e)throw new Error("NodeRandomSource: got fewer bytes than requested");const i=new Uint8Array(e);for(let s=0;s<i.length;s++)i[s]=t[s];return(0,ct.wipe)(t),i}},Object.defineProperty(it,"__esModule",{value:!0}),it.SystemRandomSource=void 0;const ht=st,lt=rt;it.SystemRandomSource=class{constructor(){return this.isAvailable=!1,this.name="",this._source=new ht.BrowserRandomSource,this._source.isAvailable?(this.isAvailable=!0,void(this.name="Browser")):(this._source=new lt.NodeRandomSource,this._source.isAvailable?(this.isAvailable=!0,void(this.name="Node")):void 0)}randomBytes(e){if(!this.isAvailable)throw new Error("System random byte generator is not available.");return this._source.randomBytes(e)}};var ut,dt={},pt={};ut=pt,Object.defineProperty(ut,"__esModule",{value:!0}),ut.mul=Math.imul||function(e,t){var i=65535&e,s=65535&t;return i*s+((e>>>16&65535)*s+i*(t>>>16&65535)<<16>>>0)|0},ut.add=function(e,t){return e+t|0},ut.sub=function(e,t){return e-t|0},ut.rotl=function(e,t){return e<<t|e>>>32-t},ut.rotr=function(e,t){return e<<32-t|e>>>t},ut.isInteger=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e},ut.MAX_SAFE_INTEGER=9007199254740991,ut.isSafeInteger=function(e){return ut.isInteger(e)&&e>=-ut.MAX_SAFE_INTEGER&&e<=ut.MAX_SAFE_INTEGER}
2,Object.defineProperty(dt,"__esModule",{value:!0});var gt=pt;function ft(e,t,i){return void 0===t&&(t=new Uint8Array(2)),void 0===i&&(i=0),t[i+0]=e>>>8,t[i+1]=e>>>0,t}function yt(e,t,i){return void 0===t&&(t=new Uint8Array(2)),void 0===i&&(i=0),t[i+0]=e>>>0,t[i+1]=e>>>8,t}function mt(e,t){return void 0===t&&(t=0),e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function wt(e,t){return void 0===t&&(t=0),(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function vt(e,t){return void 0===t&&(t=0),e[t+3]<<24|e[t+2]<<16|e[t+1]<<8|e[t]}function bt(e,t){return void 0===t&&(t=0),(e[t+3]<<24|e[t+2]<<16|e[t+1]<<8|e[t])>>>0}function _t(e,t,i){return void 0===t&&(t=new Uint8Array(4)),void 0===i&&(i=0),t[i+0]=e>>>24,t[i+1]=e>>>16,t[i+2]=e>>>8,t[i+3]=e>>>0,t}function Et(e,t,i){return void 0===t&&(t=new Uint8Array(4)),void 0===i&&(i=0),t[i+0]=e>>>0,t[i+1]=e>>>8,t[i+2]=e>>>16,t[i+3]=e>>>24,t}function St(e,t,i){return void 0===t&&(t=new Uint8Array(8)),void 0===i&&(i=0),_t(e/4294967296>>>0,t,i),_t(e>>>0,t,i+4),t}function It(e,t,i){return void 0===t&&(t=new Uint8Array(8)),void 0===i&&(i=0),Et(e>>>0,t,i),Et(e/4294967296>>>0,t,i+4),t}dt.readInt16BE=function(e,t){return void 0===t&&(t=0),(e[t+0]<<8|e[t+1])<<16>>16},dt.readUint16BE=function(e,t){return void 0===t&&(t=0),(e[t+0]<<8|e[t+1])>>>0},dt.readInt16LE=function(e,t){return void 0===t&&(t=0),(e[t+1]<<8|e[t])<<16>>16},dt.readUint16LE=function(e,t){return void 0===t&&(t=0),(e[t+1]<<8|e[t])>>>0},dt.writeUint16BE=ft,dt.writeInt16BE=ft,dt.writeUint16LE=yt,dt.writeInt16LE=yt,dt.readInt32BE=mt,dt.readUint32BE=wt,dt.readInt32LE=vt,dt.readUint32LE=bt,dt.writeUint32BE=_t,dt.writeInt32BE=_t,dt.writeUint32LE=Et,dt.writeInt32LE=Et,dt.readInt64BE=function(e,t){void 0===t&&(t=0);var i=mt(e,t),s=mt(e,t+4);return 4294967296*i+s-4294967296*(s>>31)},dt.readUint64BE=function(e,t){return void 0===t&&(t=0),4294967296*wt(e,t)+wt(e,t+4)},dt.readInt64LE=function(e,t){void 0===t&&(t=0);var i=vt(e,t);return 4294967296*vt(e,t+4)+i-4294967296*(i>>31)},dt.readUint64LE=function(e,t){void 0===t&&(t=0);var i=bt(e,t);return 4294967296*bt(e,t+4)+i},dt.writeUint64BE=St,dt.writeInt64BE=St,dt.writeUint64LE=It,dt.writeInt64LE=It,dt.readUintBE=function(e,t,i){if(void 0===i&&(i=0),e%8!==0)throw new Error("readUintBE supports only bitLengths divisible by 8");if(e/8>t.length-i)throw new Error("readUintBE: array is too short for the given b
2itLength");for(var s=0,r=1,n=e/8+i-1;n>=i;n--)s+=t[n]*r,r*=256;return s},dt.readUintLE=function(e,t,i){if(void 0===i&&(i=0),e%8!==0)throw new Error("readUintLE supports only bitLengths divisible by 8");if(e/8>t.length-i)throw new Error("readUintLE: array is too short for the given bitLength");for(var s=0,r=1,n=i;n<i+e/8;n++)s+=t[n]*r,r*=256;return s},dt.writeUintBE=function(e,t,i,s){if(void 0===i&&(i=new Uint8Array(e/8)),void 0===s&&(s=0),e%8!==0)throw new Error("writeUintBE supports only bitLengths divisible by 8");if(!gt.isSafeInteger(t))throw new Error("writeUintBE value must be an integer");for(var r=1,n=e/8+s-1;n>=s;n--)i[n]=t/r&255,r*=256;return i},dt.writeUintLE=function(e,t,i,s){if(void 0===i&&(i=new Uint8Array(e/8)),void 0===s&&(s=0),e%8!==0)throw new Error("writeUintLE supports only bitLengths divisible by 8");if(!gt.isSafeInteger(t))throw new Error("writeUintLE value must be an integer");for(var r=1,n=s;n<s+e/8;n++)i[n]=t/r&255,r*=256;return i},dt.readFloat32BE=function(e,t){return void 0===t&&(t=0),new DataView(e.buffer,e.byteOffset,e.byteLength).getFloat32(t)},dt.readFloat32LE=function(e,t){return void 0===t&&(t=0),new DataView(e.buffer,e.byteOffset,e.byteLength).getFloat32(t,!0)},dt.readFloat64BE=function(e,t){return void 0===t&&(t=0),new DataView(e.buffer,e.byteOffset,e.byteLength).getFloat64(t)},dt.readFloat64LE=function(e,t){return void 0===t&&(t=0),new DataView(e.buffer,e.byteOffset,e.byteLength).getFloat64(t,!0)},dt.writeFloat32BE=function(e,t,i){return void 0===t&&(t=new Uint8Array(4)),void 0===i&&(i=0),new DataView(t.buffer,t.byteOffset,t.byteLength).setFloat32(i,e),t},dt.writeFloat32LE=function(e,t,i){return void 0===t&&(t=new Uint8Array(4)),void 0===i&&(i=0),new DataView(t.buffer,t.byteOffset,t.byteLength).setFloat32(i,e,!0),t},dt.writeFloat64BE=function(e,t,i){return void 0===t&&(t=new Uint8Array(8)),void 0===i&&(i=0),new DataView(t.buffer,t.byteOffset,t.byteLength).setFloat64(i,e),t},dt.writeFloat64LE=function(e,t,i){return void 0===t&&(t=new Uint8Array(8)),void 0===i&&(i=0),new DataView(t.buffer,t.byteOffset,t.byteLength).setFloat64(i,e,!0),t},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.randomStringForEntropy=e.randomString=e.randomUint32=e.randomBytes=e.defaultRandomSource=void 0;const t=it,i=dt,s=nt;function r(t){return(arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.defaultRandomSource).randomBytes(t)}e.defaultRandomSource=new t.SystemRandomSource,e.randomBytes=r,e.randomUint32=function(){const t=r(4,arguments.length>0&&void 0!==arguments[0]?arguments[0]:e.defaultRandomSource),n=(0,i.readUint32LE)(t);return(0,s.wipe)(t),n};const n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function o(t){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.defaultRandomSource;if(i.length<2)throw new Error("randomString charset is too short");if(i.length>256)throw new Error("randomString charset is too long");let a="";const c=i.length,h=256-256%c;for(;t>0;){const e=r(Math.ceil(256*t/h),o);for(let s=0;s<e.length&&t>0;s++){const r=e[s];r<h&&(a+=i.charAt(r%c),t--)}(0,s.wipe)(e)}return a}e.randomString=o,e.randomStringForEntropy=function(t){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.defaultRandomSource;return o(Math.ceil(t/(Math.log(i.length)/Math.LN2)),i,s)}}(tt);var Ot={};!function(e){Object.defineProperty(e,"__esModule",{value:!0});var t=dt,i=nt;e.DIGEST_LENGTH=64,e.BLOCK_SIZE=128;var s=function(){function s(){this.digestLength=e.DIGEST_LENGTH,this.blockSize=e.BLOCK_SIZE,this._stateHi=new Int32Array(8),this._stateLo=new Int32Array(8),this._tempHi=new Int32Array(16),this._tempLo=new Int32Array(16),this._buffer=new Uint8Array(256),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this.reset()}return s.prototype._initState=function(){this._stateHi[0]=1779033703,this._stateHi[1]=3144134277,this._stateHi[2]=1013904242,this._stateHi[3]=2773480762,this._stateHi[4]=1359893119,this._stateHi[5]=2600822924,this._stateHi[6]=528734635,this._stateHi[7]=1541459225,this._stateLo[0]=4089235720,this._stateLo[1]=2227873595,this._stateLo[2]=4271175723,this._stateLo[3]=1595750129,this._stateLo[4]=2917565137,this._stateLo[5]=725511199,this._stateLo[6]=4215389547,this._stateLo[7]=327033209},s.prototype.reset=function(){return this._initState(),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this},s.prototype.clean=function(){i.wipe(this._buffer),i.wipe(this._tempHi),i.wipe(this._tempLo),this.reset()},s.prototype.update=function(t,i){if(void 0===i&&(i=t.length),this._finished)throw new Error("SHA512: can't update because hash was finished.");var s=0;if(this._bytesHashed+=i,this._bufferLength>0){for(;this._bufferLength<e.BLOCK_SIZE&&i>0;)this._buffer[this._bufferLength++]=t[s++],i--;this._bufferLength===this.blockSize&&(n(this._tempHi,this._tempLo,this._stateHi,this._stateLo,this._buffer,0,this.blockSize),this._bufferLength=0)}for(i>=this.blockSize&&(s=n(this._tempHi,this._tempLo,this._stateHi,this._stateLo,t,s,i),i%=this.blockSize);i>0;)this._buffer[this._bufferLength++]=t[s++],i--;return this},s.prototype.finish=function(e){if(!this._finished){var i=this._bytesHashed,s=this._bufferLength,r=i/536870912|0,o=i<<3,a=i%128<112?128:256;this._buffer[s]=128;for(var c=s+1;c<a-8;c++)this._buffer[c]=0;t.writeUint32BE(r,this._buffer,a-8),t.writeUint32BE(o,this._buffer,a-4),n(this._tempHi,this._tempLo,this._stateHi,this._stateLo,this._buffer,0,a),this._finished=!0}for(c=0;c<this.digestLength/8;c++)t.writeUint32BE(this._stateHi[c],e,8*c),t.writeUint32BE(this._stateLo[c],e,8*c+4);return this},s.prototype.digest=function(){var e=new Uint8Array(this.digestLength);return this.finish(e),e},s.prototype.saveState=function(){if(this._finished)throw new Error("SHA256: cannot save finished state");return{stateHi:new Int32Array(this._stateHi),stateLo:new Int32Array(this._stateLo),buffer:this._bufferLength>0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},s.prototype.restoreState=function(e){return this._stateHi.set(e.stateHi),this._stateLo.set(e.stateLo),this._bufferLength=e.bufferLength,e.buffer&&this._buffer.set(e.buffer),this._bytesHashed=e.bytesHashed,this._finished=!1,this},s.prototype.cleanSavedState=function(e){i.wipe(e.stateHi),i.wipe(e.stateLo),e.buffer&&i.wipe(e.buffer),e.bufferLength=0,e.bytesHashed=0},s}();e.SHA512=s;var r=new Int32Array([1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,
21322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591]);function n(e,i,s,n,o,a,c){for(var h,l,u,d,p,g,f,y,m=s[0],w=s[1],v=s[2],b=s[3],_=s[4],E=s[5],S=s[6],I=s[7],O=n[0],N=n[1],P=n[2],R=n[3],T=n[4],x=n[5],A=n[6],C=n[7];c>=128;){for(var L=0;L<16;L++){var U=8*L+a;e[L]=t.readUint32BE(o,U),i[L]=t.readUint32BE(o,U+4)}for(L=0;L<80;L++){var M,D,j=m,k=w,z=v,q=b,$=_,K=E,V=S,H=O,F=N,B=P,G=R,W=T,Y=x,J=A;if(p=65535&(l=C),g=l>>>16,f=65535&(h=I),y=h>>>16,p+=65535&(l=(T>>>14|_<<18)^(T>>>18|_<<14)^(_>>>9|T<<23)),g+=l>>>16,f+=65535&(h=(_>>>14|T<<18)^(_>>>18|T<<14)^(T>>>9|_<<23)),y+=h>>>16,p+=65535&(l=T&x^~T&A),g+=l>>>16,f+=65535&(h=_&E^~_&S),y+=h>>>16,h=r[2*L],p+=65535&(l=r[2*L+1]),g+=l>>>16,f+=65535&h,y+=h>>>16,h=e[L%16],g+=(l=i[L%16])>>>16,f+=65535&h,y+=h>>>16,f+=(g+=(p+=65535&l)>>>16)>>>16,p=65535&(l=d=65535&p|g<<16),g=l>>>16,f=65535&(h=u=65535&f|(y+=f>>>16)<<16),y=h>>>16,p+=65535&(l=(O>>>28|m<<4)^(m>>>2|O<<30)^(m>>>7|O<<25)),g+=l>>>16,f+=65535&(h=(m>>>28|O<<4)^(O>>>2|m<<30)^(O>>>7|m<<25)),y+=h>>>16,g+=(l=O&N^O&P^N&P)>>>16,f+=65535&(h=m&w^m&v^w&v),y+=h>>>16,M=65535&(f+=(g+=(p+=65535&l)>>>16)>>>16)|(y+=f>>>16)<<16,D=65535&p|g<<16,p=65535&(l=G),g=l>>>16,f=65535&(h=q),y=h>>>16,g+=(l=d)>>>16,f+=65535&(h=u),y+=h>>>16,w=j,v=k,b=z,_=q=65535&(f+=(g+=(p+=65535&l)>>>16)>>>16)|(y+=f>>>16)<<16,E=$,S=K,I=V,m=M,N=H,P=F,R=B,T=G=65535&p|g<<16,x=W,A=Y,C=J,O=D,L%16===15)for(U=0;U<16;U++)h=e[U],p=65535&(l=i[U]),g=l>>>16,f=65535&h,y=h>>>16,h=e[(U+9)%16],p+=65535&(l=i[(U+9)%16]),g+=l>>>16,f+=65535&h,y+=h>>>16,u=e[(U+1)%16],p+=65535&(l=((d=i[(U+1)%16])>>>1|u<<31)^(d>>>8|u<<24)^(d>>>7|u<<25)),g+=l>>>16,f+=65535&(h=(u>>>1|d<<31)^(u>>>8|d<<24)^u>>>7),y+=h>>>16,u=e[(U+14)%16],g+=(l=((d=i[(U+14)%16])>>>19|u<<13)^(u>>>29|d<<3)^(d>>>6|u<<26))>>>16,f+=65535&(h=(u>>>19|d<<13)^(d>>>29|u<<3)^u>>>6),y+=h>>>16,y+=(f+=(g+=(p+=65535&l)>>>16)>>>16)>>>16,e[U]=65535&f|y<<16,i[U]=65535&p|g<<16}p=65535&(l=O),g=l>>>16,f=65535&(h=m),y=h>>>16,h=s[0],g+=(l=n[0])>>>16,f+=65535&h,y+=h>>>16,y+=(f+=(g+=(p+=65535&l)>>>16)>>>16)>>>16,s[0]=m=65535&f|y<<16,n[0]=O=65535&p|g<<16,p=65535&(l=N),g=l>>>16,f=65535&(h=w),y=h>>>16,h=s[1],g+=(l=n[1])>>>16,f+=65535&h,y+=h>>>16,y+=(f+=(g+=(p+=65535&l)>>>16)>>>16)>>>16,s[1]=w=65535&f|y<<16,n[1]=N=65535&p|g<<16,p=65535&(l=P),g=l>>>16,f=65535&(h=v),y=h>>>16,h=s[2],g+=(l=n[2])>>>16,f+=65535&h,y+=h>>>16,y+=(f+=(g+=(p+=65535&l)>>>16)>>>16)>>>16,s[2]=v=65535&f|y<<16,n[2]=P=65535&p|g<<16,p=65535&(l=R),g=l>>>16,f=65535&(h=b),y=h>>>16,h=s[3],g+=(l=n[3])>>>16,f+=65535&h,y+=h>>>16,y+=(f+=(g+=(p+=65535&l)>>>16)>>>16)>>>16,s[3]=b=65535&f|y<<16,n[3]=R=65535&p|g<<16,p=65535&(l=T),g=l>>>16,f=65535&(h=_),y=h>>>16,h=s[4],g+=(l=n[4])>>>16,f+=65535&h,y+=h>>>16,y+=(f+=(g+=(p+=65535&l)>>>16)>>>16)>>>16,s[4]=_=65535&f|y<<16,n[4]=T=65535&p|g<<16,p=65535&(l=x),g=l>>>16,f=65535&(h=E),y=h>>>16,h=s[5],g+=(l=n[5])>>>16,f+=65535&h,y+=h>>>16,y+=(f+=(g+=(p+=65535&l)>>>16)>>>16)>>>16,s[5]=E=65535&f|y<<16,n[5]=x=65535&p|g<<16,p=65535&(l=A),g=l>>>16,f=65535&(h=S),y=h>>>16,h=s[6],g+=(l=n[6])>>>16,f+=65535&h,y+=h>>>16,y+=(f+=(g+=(p+=65535&l)>>>16)>>>16)>>>16,s[6]=S=65535&f|y<<16,n[6]=A=65535&p|g<<16,p=65535&(l=C),g=l>>>16,f=65535&(h=I),y=h>>>16,h=s[7],g+=(l=n[7])>>>16,f+=65535&h,y+=h>>>16,y+=(f+=(g+=(p+=65535&l)>>>16)>>>16)>>>16,s[7]=I=65535&f|y<<16,n[7]=C=65535&p|g<<16,a+=128,c-=128}return a}e.hash=function(e){var t=new s;t.update(e);var i=t.digest();return t.clean(),i}}(Ot),function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.convertSecretKeyToX25519=e.convertPublicKeyToX25519=e.verify=e.sign=e.extractPublicKeyFromSecretKey=e.generateKeyPair=e.generateKeyPairFromSeed=e.SEED_LENGTH=e.SECRET_KEY_LENGTH=e.PUBLIC_KEY_LENGTH=e.SIGNATURE_LENGTH=void 0;const t=tt,i=Ot,s=nt;function r(e){const t=new Float64Array(16);if(e)for(let i=0;i<e.length;i++)t[i]=e[i];return t}e.SIGNATURE_LENGTH=64,e.PUBLIC_KEY_LENGTH=32,e.SECRET_KEY_LENGTH=64,e.SEED_LENGTH=32;new Uint8Array(32)[0]=9;const n=r(),o=r([1]),a=r([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),c=r([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),h=r([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),l=r([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),u=r([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function d(e,t){for(let i=0;i<16;i++)e[i]=0|t[i]}function p(e){let t=1;for(let i=0;i<16;i++){let s=e[i]+t+65535;t=Math.floor(s/65536),e[i]=s-65536*t}e[0]+=t-1+37*(t-1)}function g(e,t,i){const s=~(i-1);for(let r=0;r<16;r++){const i=s&(e[r]^t[r]);e[r]^=i,t[r]^=i}}function f(e,t){const i=r(),s=r();for(let r=0;r<16;r++)s[r]=t[r];p(s),p(s),p(s);for(let r=0;r<2;r++){i[0]=s[0]-65517;for(let t=1;t<15;
2t++)i[t]=s[t]-65535-(i[t-1]>>16&1),i[t-1]&=65535;i[15]=s[15]-32767-(i[14]>>16&1);const e=i[15]>>16&1;i[14]&=65535,g(s,i,1-e)}for(let r=0;r<16;r++)e[2*r]=255&s[r],e[2*r+1]=s[r]>>8}function y(e,t){let i=0;for(let s=0;s<32;s++)i|=e[s]^t[s];return(1&i-1>>>8)-1}function m(e,t){const i=new Uint8Array(32),s=new Uint8Array(32);return f(i,e),f(s,t),y(i,s)}function w(e){const t=new Uint8Array(32);return f(t,e),1&t[0]}function v(e,t,i){for(let s=0;s<16;s++)e[s]=t[s]+i[s]}function b(e,t,i){for(let s=0;s<16;s++)e[s]=t[s]-i[s]}function _(e,t,i){let s,r,n=0,o=0,a=0,c=0,h=0,l=0,u=0,d=0,p=0,g=0,f=0,y=0,m=0,w=0,v=0,b=0,_=0,E=0,S=0,I=0,O=0,N=0,P=0,R=0,T=0,x=0,A=0,C=0,L=0,U=0,M=0,D=i[0],j=i[1],k=i[2],z=i[3],q=i[4],$=i[5],K=i[6],V=i[7],H=i[8],F=i[9],B=i[10],G=i[11],W=i[12],Y=i[13],J=i[14],Q=i[15];s=t[0],n+=s*D,o+=s*j,a+=s*k,c+=s*z,h+=s*q,l+=s*$,u+=s*K,d+=s*V,p+=s*H,g+=s*F,f+=s*B,y+=s*G,m+=s*W,w+=s*Y,v+=s*J,b+=s*Q,s=t[1],o+=s*D,a+=s*j,c+=s*k,h+=s*z,l+=s*q,u+=s*$,d+=s*K,p+=s*V,g+=s*H,f+=s*F,y+=s*B,m+=s*G,w+=s*W,v+=s*Y,b+=s*J,_+=s*Q,s=t[2],a+=s*D,c+=s*j,h+=s*k,l+=s*z,u+=s*q,d+=s*$,p+=s*K,g+=s*V,f+=s*H,y+=s*F,m+=s*B,w+=s*G,v+=s*W,b+=s*Y,_+=s*J,E+=s*Q,s=t[3],c+=s*D,h+=s*j,l+=s*k,u+=s*z,d+=s*q,p+=s*$,g+=s*K,f+=s*V,y+=s*H,m+=s*F,w+=s*B,v+=s*G,b+=s*W,_+=s*Y,E+=s*J,S+=s*Q,s=t[4],h+=s*D,l+=s*j,u+=s*k,d+=s*z,p+=s*q,g+=s*$,f+=s*K,y+=s*V,m+=s*H,w+=s*F,v+=s*B,b+=s*G,_+=s*W,E+=s*Y,S+=s*J,I+=s*Q,s=t[5],l+=s*D,u+=s*j,d+=s*k,p+=s*z,g+=s*q,f+=s*$,y+=s*K,m+=s*V,w+=s*H,v+=s*F,b+=s*B,_+=s*G,E+=s*W,S+=s*Y,I+=s*J,O+=s*Q,s=t[6],u+=s*D,d+=s*j,p+=s*k,g+=s*z,f+=s*q,y+=s*$,m+=s*K,w+=s*V,v+=s*H,b+=s*F,_+=s*B,E+=s*G,S+=s*W,I+=s*Y,O+=s*J,N+=s*Q,s=t[7],d+=s*D,p+=s*j,g+=s*k,f+=s*z,y+=s*q,m+=s*$,w+=s*K,v+=s*V,b+=s*H,_+=s*F,E+=s*B,S+=s*G,I+=s*W,O+=s*Y,N+=s*J,P+=s*Q,s=t[8],p+=s*D,g+=s*j,f+=s*k,y+=s*z,m+=s*q,w+=s*$,v+=s*K,b+=s*V,_+=s*H,E+=s*F,S+=s*B,I+=s*G,O+=s*W,N+=s*Y,P+=s*J,R+=s*Q,s=t[9],g+=s*D,f+=s*j,y+=s*k,m+=s*z,w+=s*q,v+=s*$,b+=s*K,_+=s*V,E+=s*H,S+=s*F,I+=s*B,O+=s*G,N+=s*W,P+=s*Y,R+=s*J,T+=s*Q,s=t[10],f+=s*D,y+=s*j,m+=s*k,w+=s*z,v+=s*q,b+=s*$,_+=s*K,E+=s*V,S+=s*H,I+=s*F,O+=s*B,N+=s*G,P+=s*W,R+=s*Y,T+=s*J,x+=s*Q,s=t[11],y+=s*D,m+=s*j,w+=s*k,v+=s*z,b+=s*q,_+=s*$,E+=s*K,S+=s*V,I+=s*H,O+=s*F,N+=s*B,P+=s*G,R+=s*W,T+=s*Y,x+=s*J,A+=s*Q,s=t[12],m+=s*D,w+=s*j,v+=s*k,b+=s*z,_+=s*q,E+=s*$,S+=s*K,I+=s*V,O+=s*H,N+=s*F,P+=s*B,R+=s*G,T+=s*W,x+=s*Y,A+=s*J,C+=s*Q,s=t[13],w+=s*D,v+=s*j,b+=s*k,_+=s*z,E+=s*q,S+=s*$,I+=s*K,O+=s*V,N+=s*H,P+=s*F,R+=s*B,T+=s*G,x+=s*W,A+=s*Y,C+=s*J,L+=s*Q,s=t[14],v+=s*D,b+=s*j,_+=s*k,E+=s*z,S+=s*q,I+=s*$,O+=s*K,N+=s*V,P+=s*H,R+=s*F,T+=s*B,x+=s*G,A+=s*W,C+=s*Y,L+=s*J,U+=s*Q,s=t[15],b+=s*D,_+=s*j,E+=s*k,S+=s*z,I+=s*q,O+=s*$,N+=s*K,P+=s*V,R+=s*H,T+=s*F,x+=s*B,A+=s*G,C+=s*W,L+=s*Y,U+=s*J,M+=s*Q,n+=38*_,o+=38*E,a+=38*S,c+=38*I,h+=38*O,l+=38*N,u+=38*P,d+=38*R,p+=38*T,g+=38*x,f+=38*A,y+=38*C,m+=38*L,w+=38*U,v+=38*M,r=1,s=n+r+65535,r=Math.floor(s/65536),n=s-65536*r,s=o+r+65535,r=Math.floor(s/65536),o=s-65536*r,s=a+r+65535,r=Math.floor(s/65536),a=s-65536*r,s=c+r+65535,r=Math.floor(s/65536),c=s-65536*r,s=h+r+65535,r=Math.floor(s/65536),h=s-65536*r,s=l+r+65535,r=Math.floor(s/65536),l=s-65536*r,s=u+r+65535,r=Math.floor(s/65536),u=s-65536*r,s=d+r+65535,r=Math.floor(s/65536),d=s-65536*r,s=p+r+65535,r=Math.floor(s/65536),p=s-65536*r,s=g+r+65535,r=Math.floor(s/65536),g=s-65536*r,s=f+r+65535,r=Math.floor(s/65536),f=s-65536*r,s=y+r+65535,r=Math.floor(s/65536),y=s-65536*r,s=m+r+65535,r=Math.floor(s/65536),m=s-65536*r,s=w+r+65535,r=Math.floor(s/65536),w=s-65536*r,s=v+r+65535,r=Math.floor(s/65536),v=s-65536*r,s=b+r+65535,r=Math.floor(s/65536),b=s-65536*r,n+=r-1+37*(r-1),r=1,s=n+r+65535,r=Math.floor(s/65536),n=s-65536*r,s=o+r+65535,r=Math.floor(s/65536),o=s-65536*r,s=a+r+65535,r=Math.floor(s/65536),a=s-65536*r,s=c+r+65535,r=Math.floor(s/65536),c=s-65536*r,s=h+r+65535,r=Math.floor(s/65536),h=s-65536*r,s=l+r+65535,r=Math.floor(s/65536),l=s-65536*r,s=u+r+65535,r=Math.floor(s/65536),u=s-65536*r,s=d+r+65535,r=Math.floor(s/65536),d=s-65536*r,s=p+r+65535,r=Math.floor(s/65536),p=s-65536*r,s=g+r+65535,r=Math.floor(s/65536),g=s-65536*r,s=f+r+65535,r=Math.floor(s/65536),f=s-65536*r,s=y+r+65535,r=Math.floor(s/65536),y=s-65536*r,s=m+r+65535,r=Math.floor(s/65536),m=s-65536*r,s=w+r+65535,r=Math.floor(s/65536),w=s-65536*r,s=v+r
2+65535,r=Math.floor(s/65536),v=s-65536*r,s=b+r+65535,r=Math.floor(s/65536),b=s-65536*r,n+=r-1+37*(r-1),e[0]=n,e[1]=o,e[2]=a,e[3]=c,e[4]=h,e[5]=l,e[6]=u,e[7]=d,e[8]=p,e[9]=g,e[10]=f,e[11]=y,e[12]=m,e[13]=w,e[14]=v,e[15]=b}function E(e,t){_(e,t,t)}function S(e,t){const i=r();let s;for(s=0;s<16;s++)i[s]=t[s];for(s=253;s>=0;s--)E(i,i),2!==s&&4!==s&&_(i,i,t);for(s=0;s<16;s++)e[s]=i[s]}function I(e,t){const i=r(),s=r(),n=r(),o=r(),a=r(),h=r(),l=r(),u=r(),d=r();b(i,e[1],e[0]),b(d,t[1],t[0]),_(i,i,d),v(s,e[0],e[1]),v(d,t[0],t[1]),_(s,s,d),_(n,e[3],t[3]),_(n,n,c),_(o,e[2],t[2]),v(o,o,o),b(a,s,i),b(h,o,n),v(l,o,n),v(u,s,i),_(e[0],a,h),_(e[1],u,l),_(e[2],l,h),_(e[3],a,u)}function O(e,t,i){for(let s=0;s<4;s++)g(e[s],t[s],i)}function N(e,t){const i=r(),s=r(),n=r();S(n,t[2]),_(i,t[0],n),_(s,t[1],n),f(e,s),e[31]^=w(i)<<7}function P(e,t,i){d(e[0],n),d(e[1],o),d(e[2],o),d(e[3],n);for(let s=255;s>=0;--s){const r=i[s/8|0]>>(7&s)&1;O(e,t,r),I(t,e),I(e,e),O(e,t,r)}}function R(e,t){const i=[r(),r(),r(),r()];d(i[0],h),d(i[1],l),d(i[2],o),_(i[3],h,l),P(e,i,t)}function T(t){if(t.length!==e.SEED_LENGTH)throw new Error(`ed25519: seed must be ${e.SEED_LENGTH} bytes`);const s=(0,i.hash)(t);s[0]&=248,s[31]&=127,s[31]|=64;const n=new Uint8Array(32),o=[r(),r(),r(),r()];R(o,s),N(n,o);const a=new Uint8Array(64);return a.set(t),a.set(n,32),{publicKey:n,secretKey:a}}e.generateKeyPairFromSeed=T,e.generateKeyPair=function(e){const i=(0,t.randomBytes)(32,e),r=T(i);return(0,s.wipe)(i),r},e.extractPublicKeyFromSecretKey=function(t){if(t.length!==e.SECRET_KEY_LENGTH)throw new Error(`ed25519: secret key must be ${e.SECRET_KEY_LENGTH} bytes`);return new Uint8Array(t.subarray(32))};const x=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function A(e,t){let i,s,r,n;for(s=63;s>=32;--s){for(i=0,r=s-32,n=s-12;r<n;++r)t[r]+=i-16*t[s]*x[r-(s-32)],i=Math.floor((t[r]+128)/256),t[r]-=256*i;t[r]+=i,t[s]=0}for(i=0,r=0;r<32;r++)t[r]+=i-(t[31]>>4)*x[r],i=t[r]>>8,t[r]&=255;for(r=0;r<32;r++)t[r]-=i*x[r];for(s=0;s<32;s++)t[s+1]+=t[s]>>8,e[s]=255&t[s]}function C(e){const t=new Float64Array(64);for(let i=0;i<64;i++)t[i]=e[i];for(let i=0;i<64;i++)e[i]=0;A(e,t)}function L(e,t){const i=r(),s=r(),c=r(),h=r(),l=r(),p=r(),g=r();return d(e[2],o),function(e,t){for(let i=0;i<16;i++)e[i]=t[2*i]+(t[2*i+1]<<8);e[15]&=32767}(e[1],t),E(c,e[1]),_(h,c,a),b(c,c,e[2]),v(h,e[2],h),E(l,h),E(p,l),_(g,p,l),_(i,g,c),_(i,i,h),function(e,t){const i=r();let s;for(s=0;s<16;s++)i[s]=t[s];for(s=250;s>=0;s--)E(i,i),1!==s&&_(i,i,t);for(s=0;s<16;s++)e[s]=i[s]}(i,i),_(i,i,c),_(i,i,h),_(i,i,h),_(e[0],i,h),E(s,e[0]),_(s,s,h),m(s,c)&&_(e[0],e[0],u),E(s,e[0]),_(s,s,h),m(s,c)?-1:(w(e[0])===t[31]>>7&&b(e[0],n,e[0]),_(e[3],e[0],e[1]),0)}e.sign=function(e,t){const s=new Float64Array(64),n=[r(),r(),r(),r()],o=(0,i.hash)(e.subarray(0,32));o[0]&=248,o[31]&=127,o[31]|=64;const a=new Uint8Array(64);a.set(o.subarray(32),32);const c=new i.SHA512;c.update(a.subarray(32)),c.update(t);const h=c.digest();c.clean(),C(h),R(n,h),N(a,n),c.reset(),c.update(a.subarray(0,32)),c.update(e.subarray(32)),c.update(t);const l=c.digest();C(l);for(let i=0;i<32;i++)s[i]=h[i];for(let i=0;i<32;i++)for(let e=0;e<32;e++)s[i+e]+=l[i]*o[e];return A(a.subarray(32),s),a},e.verify=function(t,s,n){const o=new Uint8Array(32),a=[r(),r(),r(),r()],c=[r(),r(),r(),r()];if(n.length!==e.SIGNATURE_LENGTH)throw new Error(`ed25519: signature must be ${e.SIGNATURE_LENGTH} bytes`);if(L(c,t))return!1;const h=new i.SHA512;h.update(n.subarray(0,32)),h.update(t),h.update(s);const l=h.digest();return C(l),P(a,c,l),R(c,n.subarray(32)),I(a,c),N(o,a),!y(n,o)},e.convertPublicKeyToX25519=function(e){let t=[r(),r(),r(),r()];if(L(t,e))throw new Error("Ed25519: invalid public key");let i=r(),s=r(),n=t[1];v(i,o,n),b(s,o,n),S(s,s),_(i,i,s);let a=new Uint8Array(32);return f(a,i),a},e.convertSecretKeyToX25519=function(e){const t=(0,i.hash)(e.subarray(0,32));t[0]&=248,t[31]&=127,t[31]|=64;const r=new Uint8Array(t.subarray(0,32));return(0,s.wipe)(t),r}}(et);const Nt=".",Pt="base64url",Rt="utf8",Tt="utf8",xt=":",At="did",Ct="key",Lt="base58btc",Ut="z",Mt="K36";function Dt(e){return null!=globalThis.Buffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function jt(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return null!=globalThis.Buffer&&null!=globalThis.Buffer.allocUnsafe?Dt(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}function kt(e,t){t||(t=e.reduce(((e,t)=>e+t.length),0));const i=jt(t);let s=0;for(const r of e)i.set(r,s),s+=r.length;return Dt(i)}var zt=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var i=new Uint8Array(256),s=0;s<i.length;s++)i[s]=255;for(var r=0;r<e.length;r++){var n=e.charAt(r),o=n.charCodeAt(0);if(255!==i[o])throw new TypeError(n+" is ambiguous");i[o]=r}var a=e.length,c=e.charAt(0),h=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function u(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;var t=0;if(" "!==e[t]){for(var s=0,r=0;e[t]===c;)s++,t++;for(var n=(e.length-t)*h+1>>>0,o=new Uint8Array(n);e[t];){var l=i[e.charCodeAt(t)];if(255===l)return;for(var u=0,d=n-1;(0!==l||u<r)&&-1!==d;d--,u++)l+=a*o[d]>>>0,o[d]=l%256>>>0,l=l/256>>>0;if(0!==l)throw new Error("Non-zero carry");r=u,t++}if(" "!==e[t]){for(var p=n-r;p!==n&&0===o[p];)p++;for(var g=new Uint8Array(s+(n-p)),f=s;p!==n;)g[f++]=o[p++];return g}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var i=0,s=0,r=0,n=t.length;r!==n&&0===t[r];)r++,i++;for(var o=(n-r)*l+1>>>0,h=new Uint8Array(o);r!==n;){for(var u=t[r],d=0,p=o-1;(0!==u||d<s)&&-1!==p;p--,d++)u+=256*h[p]>>>0,h[p]=u%a>>>0,u=u/a>>>0;if(0!==u)throw new Error("Non-zero carry");s=d,r++}for(var g=o-s;g!==o&&0===h[g];)g++;for(var f=c.repeat(i);g<o;++g)f+=e.charAt(h[g]);return f},decodeUnsafe:u,decode:function(e){var i=u(e);if(i)return i;throw new Error(`Non-${t} character`)}}},qt=zt;class $t{constructor(e,t,i){this.name=e,this.prefix=t,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class Kt{constructor(e,t,i){if(this.name=e,this.prefix=t,void 0===t.codePointAt(0))throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=i}decode(e){if("string"==typeof e){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name}
2 decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}throw Error("Can only multibase decode strings")}or(e){return Ht(this,e)}}class Vt{constructor(e){this.decoders=e}or(e){return Ht(this,e)}decode(e){const t=e[0],i=this.decoders[t];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Ht=(e,t)=>new Vt({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}});class Ft{constructor(e,t,i,s){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=s,this.encoder=new $t(e,t,i),this.decoder=new Kt(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Bt=e=>{let{name:t,prefix:i,encode:s,decode:r}=e;return new Ft(t,i,s,r)},Gt=e=>{let{prefix:t,name:i,alphabet:s}=e;const{encode:r,decode:n}=qt(s,i);return Bt({prefix:t,name:i,encode:r,decode:e=>(e=>{if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")})(n(e))})},Wt=e=>{let{name:t,prefix:i,bitsPerChar:s,alphabet:r}=e;return Bt({prefix:i,name:t,encode:e=>((e,t,i)=>{const s="="===t[t.length-1],r=(1<<i)-1;let n="",o=0,a=0;for(let c=0;c<e.length;++c)for(a=a<<8|e[c],o+=8;o>i;)o-=i,n+=t[r&a>>o];if(o&&(n+=t[r&a<<i-o]),s)for(;n.length*i&7;)n+="=";return n})(e,r,s),decode:e=>((e,t,i,s)=>{const r={};for(let l=0;l<t.length;++l)r[t[l]]=l;let n=e.length;for(;"="===e[n-1];)--n;const o=new Uint8Array(n*i/8|0);let a=0,c=0,h=0;for(let l=0;l<n;++l){const t=r[e[l]];if(void 0===t)throw new SyntaxError(`Non-${s} character`);c=c<<i|t,a+=i,a>=8&&(a-=8,o[h++]=255&c>>a)}if(a>=i||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o})(e,r,s,t)})},Yt=Bt({prefix:"\0",name:"identity",encode:e=>(e=>(new TextDecoder).decode(e))(e),decode:e=>(e=>(new TextEncoder).encode(e))(e)}),Jt=Object.freeze(Object.defineProperty({__proto__:null,identity:Yt},Symbol.toStringTag,{value:"Module"})),Qt=Wt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),Xt=Object.freeze(Object.defineProperty({__proto__:null,base2:Qt},Symbol.toStringTag,{value:"Module"})),Zt=Wt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),ei=Object.freeze(Object.defineProperty({__proto__:null,base8:Zt},Symbol.toStringTag,{value:"Module"})),ti=Gt({prefix:"9",name:"base10",alphabet:"0123456789"}),ii=Object.freeze(Object.defineProperty({__proto__:null,base10:ti},Symbol.toStringTag,{value:"Module"})),si=Wt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ri=Wt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),ni=Object.freeze(Object.defineProperty({__proto__:null,base16:si,base16upper:ri},Symbol.toStringTag,{value:"Module"})),oi=Wt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ai=Wt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ci=Wt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),hi=Wt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),li=Wt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ui=Wt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),di=Wt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),pi=Wt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),gi=Wt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),fi=Object.freeze(Object.defineProperty({__proto__:null,base32:oi,base32hex:li,base32hexpad:di,base32hexpadupper:pi,base32hexupper:ui,base32pad:ci,base32padupper:hi,base32upper:ai,base32z:gi},Symbol.toStringTag,{value:"Module"})),yi=Gt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),mi=Gt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),wi=Object.freeze(Object.defineProperty({__proto__:null,base36:yi,base36upper:mi},Symbol.toStringTag,{value:"Module"})),vi=Gt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),bi=Gt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),_i=Object.freeze(Object.defineProperty({__proto__:null,base58btc:vi,base58flickr:bi},Symbol.toStringTag,{value:"Module"})),Ei=Wt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
2+/",bitsPerChar:6}),Si=Wt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ii=Wt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Oi=Wt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Ni=Object.freeze(Object.defineProperty({__proto__:null,base64:Ei,base64pad:Si,base64url:Ii,base64urlpad:Oi},Symbol.toStringTag,{value:"Module"})),Pi=Array.from("\ud83d\ude80\ud83e\ude90\u2604\ud83d\udef0\ud83c\udf0c\ud83c\udf11\ud83c\udf12\ud83c\udf13\ud83c\udf14\ud83c\udf15\ud83c\udf16\ud83c\udf17\ud83c\udf18\ud83c\udf0d\ud83c\udf0f\ud83c\udf0e\ud83d\udc09\u2600\ud83d\udcbb\ud83d\udda5\ud83d\udcbe\ud83d\udcbf\ud83d\ude02\u2764\ud83d\ude0d\ud83e\udd23\ud83d\ude0a\ud83d\ude4f\ud83d\udc95\ud83d\ude2d\ud83d\ude18\ud83d\udc4d\ud83d\ude05\ud83d\udc4f\ud83d\ude01\ud83d\udd25\ud83e\udd70\ud83d\udc94\ud83d\udc96\ud83d\udc99\ud83d\ude22\ud83e\udd14\ud83d\ude06\ud83d\ude44\ud83d\udcaa\ud83d\ude09\u263a\ud83d\udc4c\ud83e\udd17\ud83d\udc9c\ud83d\ude14\ud83d\ude0e\ud83d\ude07\ud83c\udf39\ud83e\udd26\ud83c\udf89\ud83d\udc9e\u270c\u2728\ud83e\udd37\ud83d\ude31\ud83d\ude0c\ud83c\udf38\ud83d\ude4c\ud83d\ude0b\ud83d\udc97\ud83d\udc9a\ud83d\ude0f\ud83d\udc9b\ud83d\ude42\ud83d\udc93\ud83e\udd29\ud83d\ude04\ud83d\ude00\ud83d\udda4\ud83d\ude03\ud83d\udcaf\ud83d\ude48\ud83d\udc47\ud83c\udfb6\ud83d\ude12\ud83e\udd2d\u2763\ud83d\ude1c\ud83d\udc8b\ud83d\udc40\ud83d\ude2a\ud83d\ude11\ud83d\udca5\ud83d\ude4b\ud83d\ude1e\ud83d\ude29\ud83d\ude21\ud83e\udd2a\ud83d\udc4a\ud83e\udd73\ud83d\ude25\ud83e\udd24\ud83d\udc49\ud83d\udc83\ud83d\ude33\u270b\ud83d\ude1a\ud83d\ude1d\ud83d\ude34\ud83c\udf1f\ud83d\ude2c\ud83d\ude43\ud83c\udf40\ud83c\udf37\ud83d\ude3b\ud83d\ude13\u2b50\u2705\ud83e\udd7a\ud83c\udf08\ud83d\ude08\ud83e\udd18\ud83d\udca6\u2714\ud83d\ude23\ud83c\udfc3\ud83d\udc90\u2639\ud83c\udf8a\ud83d\udc98\ud83d\ude20\u261d\ud83d\ude15\ud83c\udf3a\ud83c\udf82\ud83c\udf3b\ud83d\ude10\ud83d\udd95\ud83d\udc9d\ud83d\ude4a\ud83d\ude39\ud83d\udde3\ud83d\udcab\ud83d\udc80\ud83d\udc51\ud83c\udfb5\ud83e\udd1e\ud83d\ude1b\ud83d\udd34\ud83d\ude24\ud83c\udf3c\ud83d\ude2b\u26bd\ud83e\udd19\u2615\ud83c\udfc6\ud83e\udd2b\ud83d\udc48\ud83d\ude2e\ud83d\ude46\ud83c\udf7b\ud83c\udf43\ud83d\udc36\ud83d\udc81\ud83d\ude32\ud83c\udf3f\ud83e\udde1\ud83c\udf81\u26a1\ud83c\udf1e\ud83c\udf88\u274c\u270a\ud83d\udc4b\ud83d\ude30\ud83e\udd28\ud83d\ude36\ud83e\udd1d\ud83d\udeb6\ud83d\udcb0\ud83c\udf53\ud83d\udca2\ud83e\udd1f\ud83d\ude41\ud83d\udea8\ud83d\udca8\ud83e\udd2c\u2708\ud83c\udf80\ud83c\udf7a\ud83e\udd13\ud83d\ude19\ud83d\udc9f\ud83c\udf31\ud83d\ude16\ud83d\udc76\ud83e\udd74\u25b6\u27a1\u2753\ud83d\udc8e\ud83d\udcb8\u2b07\ud83d\ude28\ud83c\udf1a\ud83e\udd8b\ud83d\ude37\ud83d\udd7a\u26a0\ud83d\ude45\ud83d\ude1f\ud83d\ude35\ud83d\udc4e\ud83e\udd32\ud83e\udd20\ud83e\udd27\ud83d\udccc\ud83d\udd35\ud83d\udc85\ud83e\uddd0\ud83d\udc3e\ud83c\udf52\ud83d\ude17\ud83e\udd11\ud83c\udf0a\ud83e\udd2f\ud83d\udc37\u260e\ud83d\udca7\ud83d\ude2f\ud83d\udc86\ud83d\udc46\ud83c\udfa4\ud83d\ude47\ud83c\udf51\u2744\ud83c\udf34\ud83d\udca3\ud83d\udc38\ud83d\udc8c\ud83d\udccd\ud83e\udd40\ud83e\udd22\ud83d\udc45\ud83d\udca1\ud83d\udca9\ud83d\udc50\ud83d\udcf8\ud83d\udc7b\ud83e\udd10\ud83e\udd2e\ud83c\udfbc\ud83e\udd75\ud83d\udea9\ud83c\udf4e\ud83c\udf4a\ud83d\udc7c\ud83d\udc8d\ud83d\udce3\ud83e\udd42"),Ri=Pi.reduce(((e,t,i)=>(e[i]=t,e)),[]),Ti=Pi.reduce(((e,t,i)=>(e[t.codePointAt(0)]=i,e)),[]);const xi=Bt({prefix:"\ud83d\ude80",name:"base256emoji",encode:function(e){return e.reduce(((e,t)=>e+=Ri[t]),"")},decode:function(e){const t=[];for(const i of e){const e=Ti[i.codePointAt(0)];if(void 0===e)throw new Error(`Non-base256emoji character: ${i}`);t.push(e)}return new Uint8Array(t)}}),Ai=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:xi},Symbol.toStringTag,{value:"Module"}));new TextEncoder,new TextDecoder;const Ci={...Jt,...Xt,...ei,...ii,...ni,...fi,...wi,..._i,...Ni,...Ai};function Li(e,t,i,s){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:i},decoder:{decode:s}}}const Ui=Li("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),Mi=Li("ascii","a",(e=>{let t="a";for(let i=0;i<e.length;i++)t+=String.fromCharCode(e[i]);return t}),(e=>{const t=jt((e=e.substring(1)).length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t})),Di={utf8:Ui,"utf-8":Ui,hex:Ci.base16,latin1:Mi,ascii:Mi,binary:Mi,...Ci};function ji(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"utf8";const i=Di[t];if(!i)throw new Error(`Unsupported encoding "${t}"`);return"utf8"!==t&&"utf-8"!==t||null==globalThis.Buffer||null==globalThis.Buffer.from?i.encoder.encode(e).substring(1):globalThis.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8")}function ki(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"utf8";const i=Di[t];if(!i)throw new Error(`Unsupported encoding "${t}"`);return"utf8"!==t&&"utf-8"!==t||null==globalThis.Buffer||null==globalThis.Buffer.from?i.decoder.decode(`${i.prefix}${e}`):Dt(globalThis.Buffer.from(e,"utf-8"))}function zi(e){return ji(ki(Ze(e),Rt),Pt)}function qi(e){const t=ki(Mt,Lt),i=Ut+ji(kt([t,e]),Lt);return[At,Ct,i].join(xt)}function $i(e){return ji(e,Pt)}function Ki(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:tt.randomBytes(32);return et.generateKeyPairFromSeed(e)}async function Vi(e,t,i,s){let r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:W.fromMiliseconds(Date.now());const n={alg:"EdDSA",typ:"JWT"},o={iss:qi(s.publicKey),sub:e,aud:t,iat:r,exp:r+i},a=function(e){return ki([zi(e.header),zi(e.payload)].join(Nt),Tt)}({header:n,payload:o});return function(e){return[zi(e.header),zi(e.payload),$i(e.signature)].join(Nt)}({header:n,payload:o,signature:et.sign(s.secretKey,a)})}var Hi={},Fi={};Object.defineProperty(Fi,"__esModule",{value:!0});var Bi=dt,Gi=nt,Wi=20;function Yi(e,t,i){for(var s=1634760805,r=857760878,n=2036477234,o=1797285236,a=i[3]<<24|i[2]<<16|i[1]<<8|i[0],c=i[7]<<24|i[6]<<16|i[5]<<8|i[4],h=i[11]<<24|i[10]<<16|i[9]<<8|i[8],l=i[15]<<24|i[14]<<16|i[13]<<8|i[12],u=i[19]<<24|i[18]<<16|i[17]<<8|i[16],d=i[23]<<24|i[22]<<16|i[21]<<8|i[20],p=i[27]<<24|i[26]<<16|i[25]<<8|i[24],g=i[31]<<24|i[30]<<16|i[29]<<8|i[28],f=t[3]<<24|t[2]<<16|t[1]<<8|t[0],y=t[7]<<24|t[6]<<16|t[5]<<8|t[4],m=t[11
2]<<24|t[10]<<16|t[9]<<8|t[8],w=t[15]<<24|t[14]<<16|t[13]<<8|t[12],v=s,b=r,_=n,E=o,S=a,I=c,O=h,N=l,P=u,R=d,T=p,x=g,A=f,C=y,L=m,U=w,M=0;M<Wi;M+=2)S=(S^=P=P+(A=(A^=v=v+S|0)>>>16|A<<16)|0)>>>20|S<<12,I=(I^=R=R+(C=(C^=b=b+I|0)>>>16|C<<16)|0)>>>20|I<<12,O=(O^=T=T+(L=(L^=_=_+O|0)>>>16|L<<16)|0)>>>20|O<<12,N=(N^=x=x+(U=(U^=E=E+N|0)>>>16|U<<16)|0)>>>20|N<<12,O=(O^=T=T+(L=(L^=_=_+O|0)>>>24|L<<8)|0)>>>25|O<<7,N=(N^=x=x+(U=(U^=E=E+N|0)>>>24|U<<8)|0)>>>25|N<<7,I=(I^=R=R+(C=(C^=b=b+I|0)>>>24|C<<8)|0)>>>25|I<<7,S=(S^=P=P+(A=(A^=v=v+S|0)>>>24|A<<8)|0)>>>25|S<<7,I=(I^=T=T+(U=(U^=v=v+I|0)>>>16|U<<16)|0)>>>20|I<<12,O=(O^=x=x+(A=(A^=b=b+O|0)>>>16|A<<16)|0)>>>20|O<<12,N=(N^=P=P+(C=(C^=_=_+N|0)>>>16|C<<16)|0)>>>20|N<<12,S=(S^=R=R+(L=(L^=E=E+S|0)>>>16|L<<16)|0)>>>20|S<<12,N=(N^=P=P+(C=(C^=_=_+N|0)>>>24|C<<8)|0)>>>25|N<<7,S=(S^=R=R+(L=(L^=E=E+S|0)>>>24|L<<8)|0)>>>25|S<<7,O=(O^=x=x+(A=(A^=b=b+O|0)>>>24|A<<8)|0)>>>25|O<<7,I=(I^=T=T+(U=(U^=v=v+I|0)>>>24|U<<8)|0)>>>25|I<<7;Bi.writeUint32LE(v+s|0,e,0),Bi.writeUint32LE(b+r|0,e,4),Bi.writeUint32LE(_+n|0,e,8),Bi.writeUint32LE(E+o|0,e,12),Bi.writeUint32LE(S+a|0,e,16),Bi.writeUint32LE(I+c|0,e,20),Bi.writeUint32LE(O+h|0,e,24),Bi.writeUint32LE(N+l|0,e,28),Bi.writeUint32LE(P+u|0,e,32),Bi.writeUint32LE(R+d|0,e,36),Bi.writeUint32LE(T+p|0,e,40),Bi.writeUint32LE(x+g|0,e,44),Bi.writeUint32LE(A+f|0,e,48),Bi.writeUint32LE(C+y|0,e,52),Bi.writeUint32LE(L+m|0,e,56),Bi.writeUint32LE(U+w|0,e,60)}function Ji(e,t,i,s,r){if(void 0===r&&(r=0),32!==e.length)throw new Error("ChaCha: key size must be 32 bytes");if(s.length<i.length)throw new Error("ChaCha: destination is shorter than source");var n,o;if(0===r){if(8!==t.length&&12!==t.length)throw new Error("ChaCha nonce must be 8 or 12 bytes");o=(n=new Uint8Array(16)).length-t.length,n.set(t,o)}else{if(16!==t.length)throw new Error("ChaCha nonce with counter must be 16 bytes");n=t,o=r}for(var a=new Uint8Array(64),c=0;c<i.length;c+=64){Yi(a,n,e);for(var h=c;h<c+64&&h<i.length;h++)s[h]=i[h]^a[h-c];Qi(n,0,o)}return Gi.wipe(a),0===r&&Gi.wipe(n),s}function Qi(e,t,i){for(var s=1;i--;)s=s+(255&e[t])|0,e[t]=255&s,s>>>=8,t++;if(s>0)throw new Error("ChaCha: counter overflow")}Fi.streamXOR=Ji,Fi.stream=function(e,t,i,s){return void 0===s&&(s=0),Gi.wipe(i),Ji(e,t,i,i,s)};var Xi={},Zi={};function es(e,t){if(e.length!==t.length)return 0;for(var i=0,s=0;s<e.length;s++)i|=e[s]^t[s];return 1&i-1>>>8}Object.defineProperty(Zi,"__esModule",{value:!0}),Zi.select=function(e,t,i){return~(e-1)&t|e-1&i},Zi.lessOrEqual=function(e,t){return(0|e)-(0|t)-1>>>31&1},Zi.compare=es,Zi.equal=function(e,t){return 0!==e.length&&0!==t.length&&0!==es(e,t)},function(e){Object.defineProperty(e,"__esModule",{value:!0});var t=Zi,i=nt;e.DIGEST_LENGTH=16;var s=function(){function t(t){this.digestLength=e.DIGEST_LENGTH,this._buffer=new Uint8Array(16),this._r=new Uint16Array(10),this._h=new Uint16Array(10),this._pad=new Uint16Array(8),this._leftover=0,this._fin=0,this._finished=!1;var i=t[0]|t[1]<<8;this._r[0]=8191&i;var s=t[2]|t[3]<<8;this._r[1]=8191&(i>>>13|s<<3);var r=t[4]|t[5]<<8;this._r[2]=7939&(s>>>10|r<<6);var n=t[6]|t[7]<<8;this._r[3]=8191&(r>>>7|n<<9);var o=t[8]|t[9]<<8;this._r[4]=255&(n>>>4|o<<12),this._r[5]=o>>>1&8190;var a=t[10]|t[11]<<8;this._r[6]=8191&(o>>>14|a<<2);var c=t[12]|t[13]<<8;this._r[7]=8065&(a>>>11|c<<5);var h=t[14]|t[15]<<8;this._r[8]=8191&(c>>>8|h<<8),this._r[9]=h>>>5&127,this._pad[0]=t[16]|t[17]<<8,this._pad[1]=t[18]|t[19]<<8,this._pad[2]=t[20]|t[21]<<8,this._pad[3]=t[22]|t[23]<<8,this._pad[4]=t[24]|t[25]<<8,this._pad[5]=t[26]|t[27]<<8,this._pad[6]=t[28]|t[29]<<8,this._pad[7]=t[30]|t[31]<<8}return t.prototype._blocks=function(e,t,i){for(var s=this._fin?0:2048,r=this._h[0],n=this._h[1],o=this._h[2],a=this._h[3],c=this._h[4],h=this._h[5],l=this._h[6],u=this._h[7],d=this._h[8],p=this._h[9],g=this._r[0],f=this._r[1],y=this._r[2],m=this._r[3],w=this._r[4],v=this._r[5],b=this._r[6],_=this._r[7],E=this._r[8],S=this._r[9];i>=16;){var I=e[t+0]|e[t+1]<<8;r+=8191&I;var O=e[t+2]|e[t+3]<<8;n+=8191&(I>>>13|O<<3);var N=e[t+4]|e[t+5]<<8;o+=8191&(O>>>10|N<<6);var P=e[t+6]|e[t+7]<<8;a+=8191&(N>>>7|P<<9);var R=e[t+8]|e[t+9]<<8;c+=8191&(P>>>4|R<<12),h+=R>>>1&8191;var T=e[t+10]|e[t+11]<<8;l+=8191&(R>>>14|T<<2);var x=e[t+12]|e[t+13]<<8;u+=8191&(T>>>11|x<<5);var A=e[t+14]|e[t+15]<<8,C=0,L=C;L+=r*g,L+=n*(5*S),L+=o*(5*E),L+=a*(5*_),C=(L+=c*(5*b))>>>13,L&=8191,L+=h*(5*v),L+=l*(5*w),L+=u*(5*m),L+=(d+=8191&(x>>>8|A<<8))*(5*y);var U=C+=(L+=(p+=A>>>5|s)*(5*f))>>>13;U+=r*f,U+=n*g,U+=o*(5*S),U+=a*(5*E),C=(U+=c*(5*_))>>>
213,U&=8191,U+=h*(5*b),U+=l*(5*v),U+=u*(5*w),U+=d*(5*m),C+=(U+=p*(5*y))>>>13,U&=8191;var M=C;M+=r*y,M+=n*f,M+=o*g,M+=a*(5*S),C=(M+=c*(5*E))>>>13,M&=8191,M+=h*(5*_),M+=l*(5*b),M+=u*(5*v),M+=d*(5*w);var D=C+=(M+=p*(5*m))>>>13;D+=r*m,D+=n*y,D+=o*f,D+=a*g,C=(D+=c*(5*S))>>>13,D&=8191,D+=h*(5*E),D+=l*(5*_),D+=u*(5*b),D+=d*(5*v);var j=C+=(D+=p*(5*w))>>>13;j+=r*w,j+=n*m,j+=o*y,j+=a*f,C=(j+=c*g)>>>13,j&=8191,j+=h*(5*S),j+=l*(5*E),j+=u*(5*_),j+=d*(5*b);var k=C+=(j+=p*(5*v))>>>13;k+=r*v,k+=n*w,k+=o*m,k+=a*y,C=(k+=c*f)>>>13,k&=8191,k+=h*g,k+=l*(5*S),k+=u*(5*E),k+=d*(5*_);var z=C+=(k+=p*(5*b))>>>13;z+=r*b,z+=n*v,z+=o*w,z+=a*m,C=(z+=c*y)>>>13,z&=8191,z+=h*f,z+=l*g,z+=u*(5*S),z+=d*(5*E);var q=C+=(z+=p*(5*_))>>>13;q+=r*_,q+=n*b,q+=o*v,q+=a*w,C=(q+=c*m)>>>13,q&=8191,q+=h*y,q+=l*f,q+=u*g,q+=d*(5*S);var $=C+=(q+=p*(5*E))>>>13;$+=r*E,$+=n*_,$+=o*b,$+=a*v,C=($+=c*w)>>>13,$&=8191,$+=h*m,$+=l*y,$+=u*f,$+=d*g;var K=C+=($+=p*(5*S))>>>13;K+=r*S,K+=n*E,K+=o*_,K+=a*b,C=(K+=c*v)>>>13,K&=8191,K+=h*w,K+=l*m,K+=u*y,K+=d*f,r=L=8191&(C=(C=((C+=(K+=p*g)>>>13)<<2)+C|0)+(L&=8191)|0),n=U+=C>>>=13,o=M&=8191,a=D&=8191,c=j&=8191,h=k&=8191,l=z&=8191,u=q&=8191,d=$&=8191,p=K&=8191,t+=16,i-=16}this._h[0]=r,this._h[1]=n,this._h[2]=o,this._h[3]=a,this._h[4]=c,this._h[5]=h,this._h[6]=l,this._h[7]=u,this._h[8]=d,this._h[9]=p},t.prototype.finish=function(e,t){void 0===t&&(t=0);var i,s,r,n,o=new Uint16Array(10);if(this._leftover){for(n=this._leftover,this._buffer[n++]=1;n<16;n++)this._buffer[n]=0;this._fin=1,this._blocks(this._buffer,0,16)}for(i=this._h[1]>>>13,this._h[1]&=8191,n=2;n<10;n++)this._h[n]+=i,i=this._h[n]>>>13,this._h[n]&=8191;for(this._h[0]+=5*i,i=this._h[0]>>>13,this._h[0]&=8191,this._h[1]+=i,i=this._h[1]>>>13,this._h[1]&=8191,this._h[2]+=i,o[0]=this._h[0]+5,i=o[0]>>>13,o[0]&=8191,n=1;n<10;n++)o[n]=this._h[n]+i,i=o[n]>>>13,o[n]&=8191;for(o[9]-=8192,s=(1^i)-1,n=0;n<10;n++)o[n]&=s;for(s=~s,n=0;n<10;n++)this._h[n]=this._h[n]&s|o[n];for(this._h[0]=65535&(this._h[0]|this._h[1]<<13),this._h[1]=65535&(this._h[1]>>>3|this._h[2]<<10),this._h[2]=65535&(this._h[2]>>>6|this._h[3]<<7),this._h[3]=65535&(this._h[3]>>>9|this._h[4]<<4),this._h[4]=65535&(this._h[4]>>>12|this._h[5]<<1|this._h[6]<<14),this._h[5]=65535&(this._h[6]>>>2|this._h[7]<<11),this._h[6]=65535&(this._h[7]>>>5|this._h[8]<<8),this._h[7]=65535&(this._h[8]>>>8|this._h[9]<<5),r=this._h[0]+this._pad[0],this._h[0]=65535&r,n=1;n<8;n++)r=(this._h[n]+this._pad[n]|0)+(r>>>16)|0,this._h[n]=65535&r;return e[t+0]=this._h[0]>>>0,e[t+1]=this._h[0]>>>8,e[t+2]=this._h[1]>>>0,e[t+3]=this._h[1]>>>8,e[t+4]=this._h[2]>>>0,e[t+5]=this._h[2]>>>8,e[t+6]=this._h[3]>>>0,e[t+7]=this._h[3]>>>8,e[t+8]=this._h[4]>>>0,e[t+9]=this._h[4]>>>8,e[t+10]=this._h[5]>>>0,e[t+11]=this._h[5]>>>8,e[t+12]=this._h[6]>>>0,e[t+13]=this._h[6]>>>8,e[t+14]=this._h[7]>>>0,e[t+15]=this._h[7]>>>8,this._finished=!0,this},t.prototype.update=function(e){var t,i=0,s=e.length;if(this._leftover){(t=16-this._leftover)>s&&(t=s);for(var r=0;r<t;r++)this._buffer[this._leftover+r]=e[i+r];if(s-=t,i+=t,this._leftover+=t,this._leftover<16)return this;this._blocks(this._buffer,0,16),this._leftover=0}if(s>=16&&(t=s-s%16,this._blocks(e,i,t),i+=t,s-=t),s){for(r=0;r<s;r++)this._buffer[this._leftover+r]=e[i+r];this._leftover+=s}return this},t.prototype.digest=function(){if(this._finished)throw new Error("Poly1305 was finished");var e=new Uint8Array(16);return this.finish(e),e},t.prototype.clean=function(){return i.wipe(this._buffer),i.wipe(this._r),i.wipe(this._h),i.wipe(this._pad),this._leftover=0,this._fin=0,this._finished=!0,this},t}();e.Poly1305=s,e.oneTimeAuth=function(e,t){var i=new s(e);i.update(t);var r=i.digest();return i.clean(),r},e.equal=function(i,s){return i.length===e.DIGEST_LENGTH&&s.length===e.DIGEST_LENGTH&&t.equal(i,s)}}(Xi),function(e){Object.defineProperty(e,"__esModule",{value:!0});var t=Fi,i=Xi,s=nt,r=dt,n=Zi;e.KEY_LENGTH=32,e.NONCE_LENGTH=12,e.TAG_LENGTH=16;var o=new Uint8Array(16),a=function(){function a(t){if(this.nonceLength=e.NONCE_LENGTH,this.tagLength=e.TAG_LENGTH,t.length!==e.KEY_LENGTH)throw new Error("ChaCha20Poly1305 needs 32-byte key");this._key=new Uint8Array(t)}return a.prototype.seal=function(e,i,r,n){if(e.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");var o=new Uint8Array(16);o.set(e,o.length-e.length);var a=new Uint8Array(32);t.stream(this._key,o,a,4);var c,h=i.length+this.tagLength;if(n){if(n.length!==h)throw new Error("ChaCha20Poly1305: incorrect destination length");c=n}else c=new Uint8Array(h);return t.streamXOR(this._key,o,i,c,4),this._authenticate(c.subarray(c.length-this.tagLength,c.length),a,c.subarray(0,c.length-this.tagLength),r),s.wipe(o),c},a.prototype.open=function(e,i,r,o){if(e.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");if(i.length<this.tagLength)return null;var a=new Uint8Array(16);a.set(e,a.length-e.length);var c=new Uint8Array(32);t.stream(this._key,a,c,4);var h=new Uint8Array(this.tagLength);if(this._authenticate(h,c,i.subarray(0,i.length-this.tagLength),r),!n.equal(h,i.subarray(i.length-this.tagLength,i.length)))return null;var l,u=i.length-this.tagLength;if(o){if(o.length!==u)throw new Error("ChaCha20Poly1305: incorrect destination length");l=o}else l=new Uint8Array(u);return t.streamXOR(this._key,a,i.subarray(0,i.length-this.tagLength),l,4),s.wipe(a),l},a.prototype.clean=function(){return s.wipe(this._key),this},a.prototype._authenticate=function(e,t,n,a){var c=new i.Poly1305(t);a&&(c.update(a),a.length%16>0&&c.update(o.subarray(a.length%16))),c.update(n),n.length%16>0&&c.update(o.subarray(n.length%16));var h=new Uint8Array(8);a&&r.writeUint64LE(a.length,h),c.update(h),r.writeUint64LE(n.length,h),c.update(h);for(var l=c.digest(),u=0;u<l.length;u++)e[u]=l[u];c.clean(),s.wipe(l),s.wipe(h)},a}();e.ChaCha20Poly1305=a}(Hi);var ts={},is={},ss={};Object.defineProperty(ss,"__esModule",{value:!0}),ss.isSerializableHash=function(e){return typeof e.saveState<"u"&&typeof e.restoreState<"u"&&typeof e.cleanSavedState<"u"},Object.defineProperty(is,"__esModule",{value:!0});var rs=ss,ns=Zi,os=nt,as=function(){function e(e,t){this._finished=!1,this._inner=new e,this._outer=new e,this.blockSize=this._outer.blockSize,this.digestLength=this._outer.digestLength;var i=new Uint8Array(this.blockSize);t.length>this.blockSize?this._inner.update(t).finish(i).clean():i.set(t);for(var s=0;s<i.length;s++)i[s]^=54;this._inner.update(i);for(s=0;s<i.length;s++)i[s]^=106;this._outer.update(i),rs.isSerializableHash(this._inner)&&rs.isSerializableHash(this._outer)&&(this._innerKeyedState=this._inner.saveState(),this._outerKeyedState=this._outer.saveState()),os.wipe(i)}return e.prototype.reset=function(){if(!rs.isSerializableHash(this._inner)||!rs.isSerializableHash(this._outer))throw new Error("hmac: can't reset() because hash doesn't implement restoreState()");return this._inner.restoreState(this._innerKeyedState),this._outer.restoreState(this._outerKeyedState),this._finished=!1,this},e.prototype.clean=function(){rs.isSerializableHash(this._inner)&&this._inner.cleanSavedState(this._innerKeyedState),rs.isSerializableHash(this._outer)&&this._outer.cleanSavedState(this._outerKeyedState),this._inner.clean(),this._outer.clean()},e.prototype.update=function(e){return this._inner.update(e),this},e.prototype.finish=function(e){return this._finished?(this._outer.finish(e),this):(this._inner.finish(e),this._outer.update(e.subarray(0,this.digestLength)).finish(e),this._finished=!0,this)},e.prototype.digest=function(){var e=new Uint8Array(this.digestLength);return this.finish(e),e},e.prototype.saveState=function(){if(!rs.isSerializableHash(this._inner))throw new Error("hmac: can't saveState() because hash doesn't implement it");return this._inner.saveState()},e.prototype.restoreState=function(e){if(!rs.isSerializableHash(this._inner)||!rs.isSerializableHash(this._outer))throw new Error("hmac: can't restoreState() because hash doesn't implement it");return this._inner.restoreState(e),this._outer.restoreState(this._outerKeyedState),this._finished=!1,this},e.prototype.cleanSavedState=function(e){if(!rs.isSerializableHash(this._inner))throw new Error("hmac: can't 
2cleanSavedState() because hash doesn't implement it");this._inner.cleanSavedState(e)},e}();is.HMAC=as,is.hmac=function(e,t,i){var s=new as(e,t);s.update(i);var r=s.digest();return s.clean(),r},is.equal=ns.equal,Object.defineProperty(ts,"__esModule",{value:!0});var cs=is,hs=nt,ls=function(){function e(e,t,i,s){void 0===i&&(i=new Uint8Array(0)),this._counter=new Uint8Array(1),this._hash=e,this._info=s;var r=cs.hmac(this._hash,i,t);this._hmac=new cs.HMAC(e,r),this._buffer=new Uint8Array(this._hmac.digestLength),this._bufpos=this._buffer.length}return e.prototype._fillBuffer=function(){this._counter[0]++;var e=this._counter[0];if(0===e)throw new Error("hkdf: cannot expand more");this._hmac.reset(),e>1&&this._hmac.update(this._buffer),this._info&&this._hmac.update(this._info),this._hmac.update(this._counter),this._hmac.finish(this._buffer),this._bufpos=0},e.prototype.expand=function(e){for(var t=new Uint8Array(e),i=0;i<t.length;i++)this._bufpos===this._buffer.length&&this._fillBuffer(),t[i]=this._buffer[this._bufpos++];return t},e.prototype.clean=function(){this._hmac.clean(),hs.wipe(this._buffer),hs.wipe(this._counter),this._bufpos=0},e}(),us=ts.HKDF=ls,ds={};!function(e){Object.defineProperty(e,"__esModule",{value:!0});var t=dt,i=nt;e.DIGEST_LENGTH=32,e.BLOCK_SIZE=64;var s=function(){function s(){this.digestLength=e.DIGEST_LENGTH,this.blockSize=e.BLOCK_SIZE,this._state=new Int32Array(8),this._temp=new Int32Array(64),this._buffer=new Uint8Array(128),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this.reset()}return s.prototype._initState=function(){this._state[0]=1779033703,this._state[1]=3144134277,this._state[2]=1013904242,this._state[3]=2773480762,this._state[4]=1359893119,this._state[5]=2600822924,this._state[6]=528734635,this._state[7]=1541459225},s.prototype.reset=function(){return this._initState(),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this},s.prototype.clean=function(){i.wipe(this._buffer),i.wipe(this._temp),this.reset()},s.prototype.update=function(e,t){if(void 0===t&&(t=e.length),this._finished)throw new Error("SHA256: can't update because hash was finished.");var i=0;if(this._bytesHashed+=t,this._bufferLength>0){for(;this._bufferLength<this.blockSize&&t>0;)this._buffer[this._bufferLength++]=e[i++],t--;this._bufferLength===this.blockSize&&(n(this._temp,this._state,this._buffer,0,this.blockSize),this._bufferLength=0)}for(t>=this.blockSize&&(i=n(this._temp,this._state,e,i,t),t%=this.blockSize);t>0;)this._buffer[this._bufferLength++]=e[i++],t--;return this},s.prototype.finish=function(e){if(!this._finished){var i=this._bytesHashed,s=this._bufferLength,r=i/536870912|0,o=i<<3,a=i%64<56?64:128;this._buffer[s]=128;for(var c=s+1;c<a-8;c++)this._buffer[c]=0;t.writeUint32BE(r,this._buffer,a-8),t.writeUint32BE(o,this._buffer,a-4),n(this._temp,this._state,this._buffer,0,a),this._finished=!0}for(c=0;c<this.digestLength/4;c++)t.writeUint32BE(this._state[c],e,4*c);return this},s.prototype.digest=function(){var e=new Uint8Array(this.digestLength);return this.finish(e),e},s.prototype.saveState=function(){if(this._finished)throw new Error("SHA256: cannot save finished state");return{state:new Int32Array(this._state),buffer:this._bufferLength>0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},s.prototype.restoreState=function(e){return this._state.set(e.state),this._bufferLength=e.bufferLength,e.buffer&&this._buffer.set(e.buffer),this._bytesHashed=e.bytesHashed,this._finished=!1,this},s.prototype.cleanSavedState=function(e){i.wipe(e.state),e.buffer&&i.wipe(e.buffer),e.bufferLength=0,e.bytesHashed=0},s}();e.SHA256=s;var r=new Int32Array([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
2734187,3204031479,3329325298]);function n(e,i,s,n,o){for(;o>=64;){for(var a=i[0],c=i[1],h=i[2],l=i[3],u=i[4],d=i[5],p=i[6],g=i[7],f=0;f<16;f++){var y=n+4*f;e[f]=t.readUint32BE(s,y)}for(f=16;f<64;f++){var m=e[f-2],w=(m>>>17|m<<15)^(m>>>19|m<<13)^m>>>10,v=((m=e[f-15])>>>7|m<<25)^(m>>>18|m<<14)^m>>>3;e[f]=(w+e[f-7]|0)+(v+e[f-16]|0)}for(f=0;f<64;f++){w=(((u>>>6|u<<26)^(u>>>11|u<<21)^(u>>>25|u<<7))+(u&d^~u&p)|0)+(g+(r[f]+e[f]|0)|0)|0,v=((a>>>2|a<<30)^(a>>>13|a<<19)^(a>>>22|a<<10))+(a&c^a&h^c&h)|0;g=p,p=d,d=u,u=l+w|0,l=h,h=c,c=a,a=w+v|0}i[0]+=a,i[1]+=c,i[2]+=h,i[3]+=l,i[4]+=u,i[5]+=d,i[6]+=p,i[7]+=g,n+=64,o-=64}return n}e.hash=function(e){var t=new s;t.update(e);var i=t.digest();return t.clean(),i}}(ds);var ps={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.sharedKey=e.generateKeyPair=e.generateKeyPairFromSeed=e.scalarMultBase=e.scalarMult=e.SHARED_KEY_LENGTH=e.SECRET_KEY_LENGTH=e.PUBLIC_KEY_LENGTH=void 0;const t=tt,i=nt;function s(e){const t=new Float64Array(16);if(e)for(let i=0;i<e.length;i++)t[i]=e[i];return t}e.PUBLIC_KEY_LENGTH=32,e.SECRET_KEY_LENGTH=32,e.SHARED_KEY_LENGTH=32;const r=new Uint8Array(32);r[0]=9;const n=s([56129,1]);function o(e){let t=1;for(let i=0;i<16;i++){let s=e[i]+t+65535;t=Math.floor(s/65536),e[i]=s-65536*t}e[0]+=t-1+37*(t-1)}function a(e,t,i){const s=~(i-1);for(let r=0;r<16;r++){const i=s&(e[r]^t[r]);e[r]^=i,t[r]^=i}}function c(e,t,i){for(let s=0;s<16;s++)e[s]=t[s]+i[s]}function h(e,t,i){for(let s=0;s<16;s++)e[s]=t[s]-i[s]}function l(e,t,i){let s,r,n=0,o=0,a=0,c=0,h=0,l=0,u=0,d=0,p=0,g=0,f=0,y=0,m=0,w=0,v=0,b=0,_=0,E=0,S=0,I=0,O=0,N=0,P=0,R=0,T=0,x=0,A=0,C=0,L=0,U=0,M=0,D=i[0],j=i[1],k=i[2],z=i[3],q=i[4],$=i[5],K=i[6],V=i[7],H=i[8],F=i[9],B=i[10],G=i[11],W=i[12],Y=i[13],J=i[14],Q=i[15];s=t[0],n+=s*D,o+=s*j,a+=s*k,c+=s*z,h+=s*q,l+=s*$,u+=s*K,d+=s*V,p+=s*H,g+=s*F,f+=s*B,y+=s*G,m+=s*W,w+=s*Y,v+=s*J,b+=s*Q,s=t[1],o+=s*D,a+=s*j,c+=s*k,h+=s*z,l+=s*q,u+=s*$,d+=s*K,p+=s*V,g+=s*H,f+=s*F,y+=s*B,m+=s*G,w+=s*W,v+=s*Y,b+=s*J,_+=s*Q,s=t[2],a+=s*D,c+=s*j,h+=s*k,l+=s*z,u+=s*q,d+=s*$,p+=s*K,g+=s*V,f+=s*H,y+=s*F,m+=s*B,w+=s*G,v+=s*W,b+=s*Y,_+=s*J,E+=s*Q,s=t[3],c+=s*D,h+=s*j,l+=s*k,u+=s*z,d+=s*q,p+=s*$,g+=s*K,f+=s*V,y+=s*H,m+=s*F,w+=s*B,v+=s*G,b+=s*W,_+=s*Y,E+=s*J,S+=s*Q,s=t[4],h+=s*D,l+=s*j,u+=s*k,d+=s*z,p+=s*q,g+=s*$,f+=s*K,y+=s*V,m+=s*H,w+=s*F,v+=s*B,b+=s*G,_+=s*W,E+=s*Y,S+=s*J,I+=s*Q,s=t[5],l+=s*D,u+=s*j,d+=s*k,p+=s*z,g+=s*q,f+=s*$,y+=s*K,m+=s*V,w+=s*H,v+=s*F,b+=s*B,_+=s*G,E+=s*W,S+=s*Y,I+=s*J,O+=s*Q,s=t[6],u+=s*D,d+=s*j,p+=s*k,g+=s*z,f+=s*q,y+=s*$,m+=s*K,w+=s*V,v+=s*H,b+=s*F,_+=s*B,E+=s*G,S+=s*W,I+=s*Y,O+=s*J,N+=s*Q,s=t[7],d+=s*D,p+=s*j,g+=s*k,f+=s*z,y+=s*q,m+=s*$,w+=s*K,v+=s*V,b+=s*H,_+=s*F,E+=s*B,S+=s*G,I+=s*W,O+=s*Y,N+=s*J,P+=s*Q,s=t[8],p+=s*D,g+=s*j,f+=s*k,y+=s*z,m+=s*q,w+=s*$,v+=s*K,b+=s*V,_+=s*H,E+=s*F,S+=s*B,I+=s*G,O+=s*W,N+=s*Y,P+=s*J,R+=s*Q,s=t[9],g+=s*D,f+=s*j,y+=s*k,m+=s*z,w+=s*q,v+=s*$,b+=s*K,_+=s*V,E+=s*H,S+=s*F,I+=s*B,O+=s*G,N+=s*W,P+=s*Y,R+=s*J,T+=s*Q,s=t[10],f+=s*D,y+=s*j,m+=s*k,w+=s*z,v+=s*q,b+=s*$,_+=s*K,E+=s*V,S+=s*H,I+=s*F,O+=s*B,N+=s*G,P+=s*W,R+=s*Y,T+=s*J,x+=s*Q,s=t[11],y+=s*D,m+=s*j,w+=s*k,v+=s*z,b+=s*q,_+=s*$,E+=s*K,S+=s*V,I+=s*H,O+=s*F,N+=s*B,P+=s*G,R+=s*W,T+=s*Y,x+=s*J,A+=s*Q,s=t[12],m+=s*D,w+=s*j,v+=s*k,b+=s*z,_+=s*q,E+=s*$,S+=s*K,I+=s*V,O+=s*H,N+=s*F,P+=s*B,R+=s*G,T+=s*W,x+=s*Y,A+=s*J,C+=s*Q,s=t[13],w+=s*D,v+=s*j,b+=s*k,_+=s*z,E+=s*q,S+=s*$,I+=s*K,O+=s*V,N+=s*H,P+=s*F,R+=s*B,T+=s*G,x+=s*W,A+=s*Y,C+=s*J,L+=s*Q,s=t[14],v+=s*D,b+=s*j,_+=s*k,E+=s*z,S+=s*q,I+=s*$,O+=s*K,N+=s*V,P+=s*H,R+=s*F,T+=s*B,x+=s*G,A+=s*W,C+=s*Y,L+=s*J,U+=s*Q,s=t[15],b+=s*D,_+=s*j,E+=s*k,S+=s*z,I+=s*q,O+=s*$,N+=s*K,P+=s*V,R+=s*H,T+=s*F,x+=s*B,A+=s*G,C+=s*W,L+=s*Y,U+=s*J,M+=s*Q,n+=38*_,o+=38*E,a+=38*S,c+=38*I,h+=38*O,l+=38*N,u+=38*P,d+=38*R,p+=38*T,g+=38*x,f+=38*A,y+=38*C,m+=38*L,w+=38*U,v+=38*M,r=1,s=n+r+65535,r=Math.floor(s/65536),n=s-65536*r,s=o+r+65535,r=Math.floor(s/65536),o=s-65536*r,s=a+r+65535,r=Math.floor(s/65536),a=s-65536*r,s=c+r+65535,r=Math.floor(s/65536),c=s-65536*r,s=h+r+65535,r=Math.floor(s/65536),h=s-65536*r,s=l+r+65535,r=Math.floor(s/65536),l=s-65536*r,s=u+r+65535,r=Math.floor(s/65536),u=s-65536*r,s=d+r+65535,r=Math.floor(s/65536),d=s-65536*r,s=p+r+65535,r=Math.floor(s/65536),p=s-65536*r,s=g+r+65535,r=Math.floor(s/65536),g=s-65536*r,s=f+r+65535,r=Math.floor(s/65536),f=s-65536*r,s=y+r+65535,r=Math.floor(s/65536),y=s-65536*r,s=m+r+65535,r=Math.floor(s/65536),m=s-65536*r,s=w+r+65535,r=Math.floor(s/65536),w=s-65536*r,s=v+r
2+65535,r=Math.floor(s/65536),v=s-65536*r,s=b+r+65535,r=Math.floor(s/65536),b=s-65536*r,n+=r-1+37*(r-1),r=1,s=n+r+65535,r=Math.floor(s/65536),n=s-65536*r,s=o+r+65535,r=Math.floor(s/65536),o=s-65536*r,s=a+r+65535,r=Math.floor(s/65536),a=s-65536*r,s=c+r+65535,r=Math.floor(s/65536),c=s-65536*r,s=h+r+65535,r=Math.floor(s/65536),h=s-65536*r,s=l+r+65535,r=Math.floor(s/65536),l=s-65536*r,s=u+r+65535,r=Math.floor(s/65536),u=s-65536*r,s=d+r+65535,r=Math.floor(s/65536),d=s-65536*r,s=p+r+65535,r=Math.floor(s/65536),p=s-65536*r,s=g+r+65535,r=Math.floor(s/65536),g=s-65536*r,s=f+r+65535,r=Math.floor(s/65536),f=s-65536*r,s=y+r+65535,r=Math.floor(s/65536),y=s-65536*r,s=m+r+65535,r=Math.floor(s/65536),m=s-65536*r,s=w+r+65535,r=Math.floor(s/65536),w=s-65536*r,s=v+r+65535,r=Math.floor(s/65536),v=s-65536*r,s=b+r+65535,r=Math.floor(s/65536),b=s-65536*r,n+=r-1+37*(r-1),e[0]=n,e[1]=o,e[2]=a,e[3]=c,e[4]=h,e[5]=l,e[6]=u,e[7]=d,e[8]=p,e[9]=g,e[10]=f,e[11]=y,e[12]=m,e[13]=w,e[14]=v,e[15]=b}function u(e,t){l(e,t,t)}function d(e,t){const i=new Uint8Array(32),r=new Float64Array(80),d=s(),p=s(),g=s(),f=s(),y=s(),m=s();for(let s=0;s<31;s++)i[s]=e[s];i[31]=127&e[31]|64,i[0]&=248,function(e,t){for(let i=0;i<16;i++)e[i]=t[2*i]+(t[2*i+1]<<8);e[15]&=32767}(r,t);for(let s=0;s<16;s++)p[s]=r[s];d[0]=f[0]=1;for(let s=254;s>=0;--s){const e=i[s>>>3]>>>(7&s)&1;a(d,p,e),a(g,f,e),c(y,d,g),h(d,d,g),c(g,p,f),h(p,p,f),u(f,y),u(m,d),l(d,g,d),l(g,p,y),c(y,d,g),h(d,d,g),u(p,d),h(g,f,m),l(d,g,n),c(d,d,f),l(g,g,d),l(d,f,m),l(f,p,r),u(p,y),a(d,p,e),a(g,f,e)}for(let s=0;s<16;s++)r[s+16]=d[s],r[s+32]=g[s],r[s+48]=p[s],r[s+64]=f[s];const w=r.subarray(32),v=r.subarray(16);(function(e,t){const i=s();for(let s=0;s<16;s++)i[s]=t[s];for(let s=253;s>=0;s--)u(i,i),2!==s&&4!==s&&l(i,i,t);for(let s=0;s<16;s++)e[s]=i[s]})(w,w),l(v,v,w);const b=new Uint8Array(32);return function(e,t){const i=s(),r=s();for(let s=0;s<16;s++)r[s]=t[s];o(r),o(r),o(r);for(let s=0;s<2;s++){i[0]=r[0]-65517;for(let t=1;t<15;t++)i[t]=r[t]-65535-(i[t-1]>>16&1),i[t-1]&=65535;i[15]=r[15]-32767-(i[14]>>16&1);const e=i[15]>>16&1;i[14]&=65535,a(r,i,1-e)}for(let s=0;s<16;s++)e[2*s]=255&r[s],e[2*s+1]=r[s]>>8}(b,v),b}function p(e){return d(e,r)}function g(t){if(t.length!==e.SECRET_KEY_LENGTH)throw new Error(`x25519: seed must be ${e.SECRET_KEY_LENGTH} bytes`);const i=new Uint8Array(t);return{publicKey:p(i),secretKey:i}}e.scalarMult=d,e.scalarMultBase=p,e.generateKeyPairFromSeed=g,e.generateKeyPair=function(e){const s=(0,t.randomBytes)(32,e),r=g(s);return(0,i.wipe)(s),r},e.sharedKey=function(t,i){let s=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(t.length!==e.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect secret key length");if(i.length!==e.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect public key length");const r=d(t,i);if(s){let e=0;for(let t=0;t<r.length;t++)e|=r[t];if(0===e)throw new Error("X25519: invalid shared key")}return r}}(ps);var gs=globalThis&&globalThis.__spreadArray||function(e,t,i){if(i||2===arguments.length)for(var s,r=0,n=t.length;r<n;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},fs=function(e,t,i){this.name=e,this.version=t,this.os=i,this.type="browser"},ys=function(e){this.version=e,this.type="node",this.name="node",this.os=a.platform},ms=function(e,t,i,s){this.name=e,this.version=t,this.os=i,this.bot=s,this.type="bot-device"},ws=function(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null},vs=function(){this.type="react-native",this.name="react-native",this.version=null,this.os=null},bs=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,_s=3,Es=[["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;
2\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",/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/]],Ss=[["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 Is(e){return e?Os(e):typeof document>"u"&&typeof navigator<"u"&&"ReactNative"===navigator.product?new vs:typeof navigator<"u"?Os(navigator.userAgent):function(){var e=typeof a<"u"&&a.version;return e?new ys(a.version.slice(1)):null}()}function Os(e){var t=function(e){return""!==e&&Es.reduce((function(t,i){var s=i[0],r=i[1];if(t)return t;var n=r.exec(e);return!!n&&[s,n]}),!1)}(e);if(!t)return null;var i=t[0],s=t[1];if("searchbot"===i)return new ws;var r=s[1]&&s[1].split(".").join("_").split("_").slice(0,3);r?r.length<_s&&(r=gs(gs([],r,!0),function(e){for(var t=[],i=0;i<e;i++)t.push("0");return t}(_s-r.length),!0)):r=[];var n=r.join("."),o=function(e){for(var t=0,i=Ss.length;t<i;t++){var s=Ss[t],r=s[0];if(s[1].exec(e))return r}return null}(e),a=bs.exec(e);return a&&a[1]?new ms(i,n,o,a[1]):new fs(i,n,o)}var Ns={};function Ps(e){let t;return typeof window<"u"&&typeof window[e]<"u"&&(t=window[e]),t}function Rs(e){const t=Ps(e);if(!t)throw new Error(`${e} is not defined in Window`);return t}Object.defineProperty(Ns,"__esModule",{value:!0}),Ns.getLocalStorage=Ns.getLocalStorageOrThrow=Ns.getCrypto=Ns.getCryptoOrThrow=As=Ns.getLocation=Ns.getLocationOrThrow=xs=Ns.getNavigator=Ns.getNavigatorOrThrow=Ts=Ns.getDocument=Ns.getDocumentOrThrow=Ns.getFromWindowOrThrow=Ns.getFromWindow=void 0,Ns.getFromWindow=Ps,Ns.getFromWindowOrThrow=Rs,Ns.getDocumentOrThrow=function(){return Rs("document")};var Ts=Ns.getDocument=function(){return Ps("document")};Ns.getNavigatorOrThrow=function(){return Rs("navigator")};var xs=Ns.getNavigator=function(){return Ps("navigator")};Ns.getLocationOrThrow=function(){return Rs("location")};var As=Ns.getLocation=function(){return Ps("location")};Ns.getCryptoOrThrow=function(){return Rs("crypto")},Ns.getCrypto=function(){return Ps("crypto")},Ns.getLocalStorageOrThrow=function(){return Rs("localStorage")},Ns.getLocalStorage=function(){return Ps("localStorage")};var Cs={};Object.defineProperty(Cs,"__esModule",{value:!0});var Ls=Cs.getWindowMetadata=void 0;const Us=Ns;Ls=Cs.getWindowMetadata=function(){let e,t;try{e=Us.getDocumentOrThrow(),t=Us.getLocationOrThrow()}catch{return null}function i(){for(var t=arguments.length,i=new Array(t),s=0;s<t;s++)i[s]=arguments[s];const r=e.getElementsByTagName("meta");for(let e=0;e<r.length;e++){const t=r[e],s=["itemprop","property","name"].map((e=>t.getAttribute(e))).filter((e=>!!e&&i.includes(e)));if(s.length&&s){const e=t.getAttribute("content");if(e)return e}}return""}const s=function(){let t=i("name","og:site_name","og:title","twitter:title");return t||(t=e.title),t}();return{description:i("description","og:description","twitter:description","keywords"),url:t.origin,icons:function(){const i=e.getElementsByTagName("link"),s=[];for(let e=0;e<i.length;e++){const r=i[e],n=r.getAttribute("rel");if(n&&n.toLowerCase().indexOf("icon")>-1){const e=r.getAttribute("href");if(e)if(-1===e.toLowerCase().indexOf("https:")&&-1===e.toLowerCase().indexOf("http:")&&0!==e.indexOf("//")){let i=t.protocol+"//"+t.host;if(0===e.indexOf("/"))i+=e;else{const s=t.pathname.split("/");s.pop();i+=s.join("/")+"/"+e}s.push(i)}else if(0===e.indexOf("//")){const i=t.protocol+e;s.push(i)}else s.push(e)}}return s}(),name:s}};var Ms={},Ds=e=>encodeURIComponent(e).replace(/[!'()*]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)),js="%[a-f0-9]{2}",ks=new RegExp("("+js+")|([^%]+?)","gi"),zs=new RegExp("("+js+")+","gi");function qs(e,t){try{return[decodeURIComponent(e.join(""))]}catch{}if(1===e.length)return e;t=t||1;var i=e.slice(0,t),s=e.slice(t);return Array.prototype.concat.call([],qs(i),qs(s))}function $s(e){try{return decodeURIComponent(e)}catch{for(var t=e.match(ks)||[],i=1;i<t.length;i++)t=(e=qs(t,i).join("")).match(ks)||[];return e}}var Ks=function(e){if("string"!=typeof e)throw new TypeError("Expected `encodedURI` to be of type `string`, got `"+typeof e+"`");try{return e=e.replace(/\+/g," "),decodeURIComponent(e)}catch{return function(e){for(var t={"%FE%FF":"\ufffd\ufffd","%FF%FE":"\ufffd\ufffd"},i=zs.exec(e);i;){try{t[i[0]]=decodeURIComponent(i[0])}catch{var s=$s(i[0]);s!==i[0]&&(t[i[0]]=s)}i=zs.exec(e)}t["%C2"]="\ufffd";for(var r=Object.keys(t),n=0;n<r.length;n++){var o=r[n];e=e.replace(new RegExp(o,"g"),t[o])}return e}(e)}},Vs=(e,t)=>{if("string"!=typeof e||"string"!=typeof t)throw new TypeError("Expected the arguments to be of type `string`");if(""===t)return[e];const i=e.indexOf(t);return-1===i?[e]:[e.slice(0,i),e.slice(i+t.length)]},Hs=function(e,t){for(var i={},s=Object.keys(e),r=Array.isArray(t),n=0;n<s.length;n++){var o=s[n],a=e[o];(r?-1!==t.indexOf(o):t(o,a,e))&&(i[o]=a)}return i};!function(e){const t=Ds,i=Ks,s=Vs,r=Hs,n=Symbol("encodeFragmentIdentifier");function o(e){if("string"!=typeof e||1!==e.length)throw new TypeError("arrayFormatSeparator must be single character string")}function a(e,i){return i.encode?i.strict?t(e):encodeURIComponent(e):e}function c(e,t){return t.decode?i(e):e}function h(e){return Array.isArray(e)?e.sort():"object"==typeof e?h(Object.keys(e)).sort(((e,t)=>Number(e)-Number(t))).map((t=>e[t])):e}function l(e){const t=e.indexOf("#");return-1!==t&&(e=e.slice(0,t)),e}function u(e){const t=(e=l(e)).indexOf("?");return-1===t?"":e.slice(t+1)}function d(e,t){return t.parseNumbers&&!Number.isNaN(Number(e))&&"string"==typeof e&&""!==e.trim()?e=Number(e):t.parseBooleans&&null!==e&&("true"===e.toLowerCase()||"false"===e.toLowerCase())&&(e="true"===e.toLowerCase()),e}function p(e,t){o((t=Object.assign({decode:!0,sort:!0,arrayFormat:"none",arrayFormatSeparator:",",parseNumbers:!1,parseBooleans:!1},t)).arrayFormatSeparator);const i=function(e){let t;switch(e.arrayFormat){case"index":return(e,i,s)=>{t=/\[(\d*)\]$/.exec(e),e=e.replace(/\[\d*\]$/,""),t?(void 0===s[e]&&(s[e]={}),s[e][t[1]]=i):s[e]=i};case"bracket":return(e,i,s)=>{t=/(\[\])$/.exec(e),e=e.replace(/\[\]$/,""),t?void 0!==s[e]?s[e]=[].concat(s[e],i):s[e]=[i]:s[e]=i};case"colon-list-separator":return(e,i,s)=>{t=/(:list)$/.exec(e),e=e.replace(/:list$/,""),t?void 0!==s[e]?s[e]=[].concat(s[e],i):s[e]=[i]:s[e]=i};case"comma":case"separator":return(t,i,s)=>{const r="string"==typeof i&&i.includes(e.arrayFormatSeparator),n="string"==typeof i&&!r&&c(i,e).includes(e.arrayFormatSeparator);i=n?c(i,e):i;const o=r||n?i.split(e.arrayFormatSeparator).map((t=>c(t,e))):null===i?i:c(i,e);s[t]=o};case"bracket-separator":return(t,i,s)=>{const r=/(\[\])$/.test(t);if(t=t.replace(/\[\]$/,""),!r)return void(s[t]=i&&c(i,e));const n=null===i?[]:i.split(e.arrayFormatSeparator).map((t=>c(t,e)));void 0!==s[t]?s[t]=[].concat(s[t],n):s[t]=n};default:return(e,t,i)=>{void 0!==i[e]?i[e]=[].concat(i[e],t):i[e]=t}}}(t),r=Object.create(null);if("string"!=typeof e||!(e=e.trim().replace(/^[?#&]/,"")))return r;for(const n of e.split("&")){if(""===n)continue;let[e,o]=s(t.decode?n.replace(/\+/g," "):n,"=");o=void 0===o?null:["comma","separator","bracket-separator"].includes(t.arrayFormat)?o:c(o,t),i(c(e,t),o,r)}for(const s of Object.keys(r)){const e=r[s];if("object"==typeof e&&null!==e)for(const i of Object.keys(e))e[i]=d(e[i],t);else r[s]=d(e,t)}return!1===t.sort?r:(!0===t.sort?Object.keys(r).sort():Object.keys(r).sort(t.sort)).reduce(((e,t)=>{const i=r[t];return i&&"object"==typeof i&&!Array.isArray(i)?e[t]=h(i):e[t]=i,e}),Object.create(null))}e.extract=u,e.parse=p,e.stringify=(e,t)=>{if(!e)return"";o((t=Object.assign({encode:!0,strict:!0,arrayFormat:"none",arrayFormatSeparator:","},t)).arrayFormatSeparator);const i=i=>t.skipNull&&(e=>null==e)(e[i])||t.skipEmptyString&&""===e[i],s=function(e){switch(e.arrayFormat){case"index":return t=>(i,s)=>{const r=i.length;return void 0===s||e.skipNull&&null===s||e.skipEmptyString&&""===s?i:null===s?[...i,[a(t,e),"[",r,"]"].join("")]:[...i,[a(t,e),"[",a(r,e),"]=",a(s,e)].join("")]};case"bracket":return t=>(i,s)=>void 0===s||e.skipNull&&null===s||e.skipEmptyString&&""===s?i:null===s?[...i,[a(t,e),"[]"].join("")]:[...i,[a(t,e),"[]=",a(s,e)].join("")];case"colon-list-separator":return t=>(i,s)=>void 0===s||e.skipNull&&null===s||e.skipEmptyString&&""===s?i:null===s?[...i,[a(t,e),":list="].join("")]:[...i,[a(t,e),":list=",a(s,e)].join("")];case"comma":case"separator":case"bracket-separator":{const t="bracket-separator"===e.arrayFormat?"[]=":"=";return i=>(s,r)=>void 0===r||e.skipNull&&null===r||e.skipEmptyString&&""===r?s:(r=null===r?"":r,0===s.length?[[a(i,e),t,a(r,e)].join("")]:[[s,a(r,e)].join(e.arrayFormatSeparator)])}default:return t=>(i,s)=>void 0===s||e.skipNull&&null===s||e.skipEmptyString&&""===s?i:null===s?[...i,a(t,e)]:[...i,[a(t,e),"=",a(s,e)].join("")]}}(t),r={};
2for(const o of Object.keys(e))i(o)||(r[o]=e[o]);const n=Object.keys(r);return!1!==t.sort&&n.sort(t.sort),n.map((i=>{const r=e[i];return void 0===r?"":null===r?a(i,t):Array.isArray(r)?0===r.length&&"bracket-separator"===t.arrayFormat?a(i,t)+"[]":r.reduce(s(i),[]).join("&"):a(i,t)+"="+a(r,t)})).filter((e=>e.length>0)).join("&")},e.parseUrl=(e,t)=>{t=Object.assign({decode:!0},t);const[i,r]=s(e,"#");return Object.assign({url:i.split("?")[0]||"",query:p(u(e),t)},t&&t.parseFragmentIdentifier&&r?{fragmentIdentifier:c(r,t)}:{})},e.stringifyUrl=(t,i)=>{i=Object.assign({encode:!0,strict:!0,[n]:!0},i);const s=l(t.url).split("?")[0]||"",r=e.extract(t.url),o=e.parse(r,{sort:!1}),c=Object.assign(o,t.query);let h=e.stringify(c,i);h&&(h=`?${h}`);let u=function(e){let t="";const i=e.indexOf("#");return-1!==i&&(t=e.slice(i)),t}(t.url);return t.fragmentIdentifier&&(u=`#${i[n]?a(t.fragmentIdentifier,i):t.fragmentIdentifier}`),`${s}${h}${u}`},e.pick=(t,i,s)=>{s=Object.assign({parseFragmentIdentifier:!0,[n]:!1},s);const{url:o,query:a,fragmentIdentifier:c}=e.parseUrl(t,s);return e.stringifyUrl({url:o,query:r(a,i),fragmentIdentifier:c},s)},e.exclude=(t,i,s)=>{const r=Array.isArray(i)?e=>!i.includes(e):(e,t)=>!i(e,t);return e.pick(t,r,s)}}(Ms);const Fs={waku:{publish:"waku_publish",batchPublish:"waku_batchPublish",subscribe:"waku_subscribe",batchSubscribe:"waku_batchSubscribe",subscription:"waku_subscription",unsubscribe:"waku_unsubscribe",batchUnsubscribe:"waku_batchUnsubscribe"},irn:{publish:"irn_publish",batchPublish:"irn_batchPublish",subscribe:"irn_subscribe",batchSubscribe:"irn_batchSubscribe",subscription:"irn_subscription",unsubscribe:"irn_unsubscribe",batchUnsubscribe:"irn_batchUnsubscribe"},iridium:{publish:"iridium_publish",batchPublish:"iridium_batchPublish",subscribe:"iridium_subscribe",batchSubscribe:"iridium_batchSubscribe",subscription:"iridium_subscription",unsubscribe:"iridium_unsubscribe",batchUnsubscribe:"iridium_batchUnsubscribe"}};function Bs(e,t){return e.includes(":")?[e]:t.chains||[]}const Gs="base10",Ws="base16",Ys="base64pad",Js="utf8",Qs=0,Xs=1,Zs=0,er=1,tr=12,ir=32;function sr(){return ji(tt.randomBytes(ir),Ws)}function rr(e){return ji(ds.hash(ki(e,Js)),Ws)}function nr(e){return Number(ji(e,Gs))}function or(e){const t=function(e){return ki(`${e}`,Gs)}(typeof e.type<"u"?e.type:Qs);if(nr(t)===Xs&&typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const i=typeof e.senderPublicKey<"u"?ki(e.senderPublicKey,Ws):void 0,s=typeof e.iv<"u"?ki(e.iv,Ws):tt.randomBytes(tr);return function(e){if(nr(e.type)===Xs){if(typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return ji(kt([e.type,e.senderPublicKey,e.iv,e.sealed]),Ys)}return ji(kt([e.type,e.iv,e.sealed]),Ys)}({type:t,sealed:new Hi.ChaCha20Poly1305(ki(e.symKey,Ws)).seal(s,ki(e.message,Js)),iv:s,senderPublicKey:i})}function ar(e){const t=ki(e,Ys),i=t.slice(Zs,er),s=er;if(nr(i)===Xs){const e=s+ir,r=e+tr,n=t.slice(s,e),o=t.slice(e,r);return{type:i,sealed:t.slice(r),iv:o,senderPublicKey:n}}const r=s+tr,n=t.slice(s,r);return{type:i,sealed:t.slice(r),iv:n}}function cr(e){const t=(null===e||void 0===e?void 0:e.type)||Qs;if(t===Xs){if(typeof(null===e||void 0===e?void 0:e.senderPublicKey)>"u")throw new Error("missing sender public key");if(typeof(null===e||void 0===e?void 0:e.receiverPublicKey)>"u")throw new Error("missing receiver public key")}return{type:t,senderPublicKey:null===e||void 0===e?void 0:e.senderPublicKey,receiverPublicKey:null===e||void 0===e?void 0:e.receiverPublicKey}}function hr(e){return e.type===Xs&&"string"==typeof e.senderPublicKey&&"string"==typeof e.receiverPublicKey}var lr=Object.defineProperty,ur=Object.getOwnPropertySymbols,dr=Object.prototype.hasOwnProperty,pr=Object.prototype.propertyIsEnumerable,gr=(e,t,i)=>t in e?lr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,fr=(e,t)=>{for(var i in t||(t={}))dr.call(t,i)&&gr(e,i,t[i]);if(ur)for(var i of ur(t))pr.call(t,i)&&gr(e,i,t[i]);return e};const yr="ReactNative",mr={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},wr="js";function vr(){return typeof a<"u"&&typeof a.versions<"u"&&typeof a.versions.node<"u"}function br(){return!Ts()&&!!xs()&&navigator.product===yr}function _r(){return!vr()&&!!xs()}function Er(){return br()?mr.reactNative:vr()?mr.node:_r()?mr.browser:mr.unknown}function Sr(e,t,i){const s=function(){if(Er()===mr.reactNative&&typeof global<"u"&&typeof(null==global?void 0:global.Platform)<"u"){const{OS:e,Version:t}=global.Platform;return[e,t].join("-")}const e=Is();if(null===e)return"unknown";const t=e.os?e.os.replace(" ","").toLowerCase():"unknown";return"browser"===e.type?[t,e.name,e.version].join("-"):[t,e.version].join("-")}(),r=function(){var e;const t=Er();return t===mr.browser?[t,(null==(e=As())?void 0:e.host)||"unknown"].join(":"):t}();return[[e,t].join("-"),[wr,i].join("-"),s,r].join("/")}function Ir(e){let{protocol:t,version:i,relayUrl:s,sdkVersion:r,auth:n,projectId:o,useOnCloseEvent:a}=e;const c=s.split("?"),h={auth:n,ua:Sr(t,i,r),projectId:o,useOnCloseEvent:a||void 0},l=function(e,t){let i=Ms.parse(e);return i=fr(fr({},i),t),Ms.stringify(i)}(c[1]||"",h);return c[0]+"?"+l}function Or(e,t){return e.filter((e=>t.includes(e))).length===e.length}function Nr(e){return Object.fromEntries(e.entries())}function Pr(e){return new Map(Object.entries(e))}function Rr(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:W.FIVE_MINUTES,t=arguments.length>1?arguments[1]:void 0;const i=W.toMiliseconds(e||W.FIVE_MINUTES);let s,r,n;return{resolve:e=>{n&&s&&(clearTimeout(n),s(e))},reject:e=>{n&&r&&(clearTimeout(n),r(e))},done:()=>new Promise(((e,o)=>{n=setTimeout((()=>{o(new Error(t))}),i),s=e,r=o}))}}function Tr(e,t,i){return new Promise((async(s,r)=>{const n=setTimeout((()=>r(new Error(i))),t);try{s(await e)}catch(o){r(o)}clearTimeout(n)}))}function xr(e,t){if("string"==typeof t&&t.startsWith(`${e}:`))return t;if("topic"===e.toLowerCase()){if("string"!=typeof t)throw new Error('Value must be "string" for expirer target type: topic');return`topic:${t}`}if("id"===e.toLowerCase()){if("number"!=typeof t)throw new Error('Value must be "number" for expirer target type: id');return`id:${t}`}throw new Error(`Unknown expirer target type: ${e}`)}function Ar(e){const[t,i]=e.split(":"),s={id:void 0,topic:void 0};if("topic"===t&&"string"==typeof i)s.topic=i;else{if("id"!==t||!Number.isInteger(Number(i)))throw new Error(`Invalid target, expected id:number or topic:string, got ${t}:${i}`);s.id=Number(i)}return s}function Cr(e,t){return W.fromMiliseconds((t||Date.now())+W.toMiliseconds(e))}function Lr(e){return Date.now()>=W.toMiliseconds(e)}function Ur(e,t){return`${e}${t?`:${t}`:""}`}function Mr(e){return(null===e||void 0===e?void 0:e.relay)||{protocol:"irn"}}function Dr(e){const t=Fs[e];if(typeof t>"u")throw new Error(`Relay Protocol not supported: ${e}`);return t}var jr=Object.defineProperty,kr=Object.getOwnPropertySymbols,zr=Object.prototype.hasOwnProperty,qr=Object.prototype.propertyIsEnumerable,$r=(e,t,i)=>t in e?jr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i;function Kr(e){const t={},i="relay"+(arguments.length>1&&void 0!==arguments[1]?arguments[1]:"-");return Object.keys(e).forEach((s=>{if(s.startsWith(i)){const r=s.replace(i,""),n=e[s];t[r]=n}})),t}function Vr(e){return e.startsWith("//")?e.substring(2):e}function Hr(e){return`${e.protocol}
2:${e.topic}@${e.version}?`+Ms.stringify(((e,t)=>{for(var i in t||(t={}))zr.call(t,i)&&$r(e,i,t[i]);if(kr)for(var i of kr(t))qr.call(t,i)&&$r(e,i,t[i]);return e})({symKey:e.symKey},function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"-";const i={};return Object.keys(e).forEach((s=>{const r="relay"+t+s;e[s]&&(i[r]=e[s])})),i}(e.relay)))}function Fr(e){const t=[];return e.forEach((e=>{const[i,s]=e.split(":");t.push(`${i}:${s}`)})),t}const Br={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}},Gr={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 Wr(e,t){const{message:i,code:s}=Gr[e];return{message:t?`${i} ${t}`:i,code:s}}function Yr(e,t){const{message:i,code:s}=Br[e];return{message:t?`${i} ${t}`:i,code:s}}function Jr(e,t){return!!Array.isArray(e)&&(!(typeof t<"u"&&e.length)||e.every(t))}function Qr(e){return Object.getPrototypeOf(e)===Object.prototype&&Object.keys(e).length}function Xr(e){return typeof e>"u"}function Zr(e,t){return!(!t||!Xr(e))||"string"==typeof e&&!!e.trim().length}function en(e,t){return!(!t||!Xr(e))||"number"==typeof e&&!isNaN(e)}function tn(e){return!(!Zr(e,!1)||!e.includes(":"))&&2===e.split(":").length}function sn(e){let t=!0;return Jr(e)?e.length&&(t=e.every((e=>Zr(e,!1)))):t=!1,t}function rn(e,t,i){let s=null;return Object.entries(e).forEach((e=>{let[r,n]=e;if(s)return;const o=function(e,t,i){let s=null;return Jr(t)&&t.length?t.forEach((e=>{s||tn(e)||(s=Yr("UNSUPPORTED_CHAINS",`${i}, chain ${e} should be a string and conform to "namespace:chainId" format`))})):tn(e)||(s=Yr("UNSUPPORTED_CHAINS",`${i}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),s}(r,Bs(r,n),`${t} ${i}`);o&&(s=o)})),s}function nn(e,t){let i=null;return Jr(e)?e.forEach((e=>{i||function(e){if(Zr(e,!1)&&e.includes(":")){const t=e.split(":");if(3===t.length){const e=t[0]+":"+t[1];return!!t[2]&&tn(e)}}return!1}(e)||(i=Yr("UNSUPPORTED_ACCOUNTS",`${t}, account ${e} should be a string and conform to "namespace:chainId:address" format`))})):i=Yr("UNSUPPORTED_ACCOUNTS",`${t}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),i}function on(e,t){let i=null;return Object.values(e).forEach((e=>{if(i)return;const s=function(e,t){let i=null;return sn(null===e||void 0===e?void 0:e.methods)?sn(null===e||void 0===e?void 0:e.events)||(i=Yr("UNSUPPORTED_EVENTS",`${t}
2, events should be an array of strings or empty array for no events`)):i=Yr("UNSUPPORTED_METHODS",`${t}, methods should be an array of strings or empty array for no methods`),i}(e,`${t}, namespace`);s&&(i=s)})),i}function an(e,t){let i=null;if(e&&Qr(e)){const s=on(e,t);s&&(i=s);const r=function(e,t){let i=null;return Object.values(e).forEach((e=>{if(i)return;const s=nn(null===e||void 0===e?void 0:e.accounts,`${t} namespace`);s&&(i=s)})),i}(e,t);r&&(i=r)}else i=Wr("MISSING_OR_INVALID",`${t}, namespaces should be an object with data`);return i}function cn(e){return Zr(e.protocol,!0)}function hn(e){return typeof e<"u"&&null!==typeof e}function ln(e,t){return!(!tn(t)||!function(e){const t=[];return Object.values(e).forEach((e=>{t.push(...Fr(e.accounts))})),t}(e).includes(t))}function un(e,t,i){return!!Zr(i,!1)&&function(e,t){const i=[];return Object.values(e).forEach((e=>{Fr(e.accounts).includes(t)&&i.push(...e.methods)})),i}(e,t).includes(i)}function dn(e,t,i){return!!Zr(i,!1)&&function(e,t){const i=[];return Object.values(e).forEach((e=>{Fr(e.accounts).includes(t)&&i.push(...e.events)})),i}(e,t).includes(i)}function pn(e,t,i){let s=null;const r=function(e){const t={};return Object.keys(e).forEach((i=>{var s;i.includes(":")?t[i]=e[i]:null==(s=e[i].chains)||s.forEach((s=>{t[s]={methods:e[i].methods,events:e[i].events}}))})),t}(e),n=function(e){const t={};return Object.keys(e).forEach((i=>{var s;i.includes(":")?t[i]=e[i]:null===(s=Fr(e[i].accounts))||void 0===s||s.forEach((s=>{t[s]={accounts:e[i].accounts.filter((e=>e.includes(`${s}:`))),methods:e[i].methods,events:e[i].events}}))})),t}(t),o=Object.keys(r),a=Object.keys(n),c=gn(Object.keys(e)),h=gn(Object.keys(t)),l=c.filter((e=>!h.includes(e)));return l.length&&(s=Wr("NON_CONFORMING_NAMESPACES",`${i} namespaces keys don't satisfy requiredNamespaces.\n      Required: ${l.toString()}\n      Received: ${Object.keys(t).toString()}`)),Or(o,a)||(s=Wr("NON_CONFORMING_NAMESPACES",`${i} namespaces chains don't satisfy required namespaces.\n      Required: ${o.toString()}\n      Approved: ${a.toString()}`)),Object.keys(t).forEach((e=>{if(!e.includes(":")||s)return;const r=Fr(t[e].accounts);r.includes(e)||(s=Wr("NON_CONFORMING_NAMESPACES",`${i} namespaces accounts don't satisfy namespace accounts for ${e}\n        Required: ${e}\n        Approved: ${r.toString()}`))})),o.forEach((e=>{s||(Or(r[e].methods,n[e].methods)?Or(r[e].events,n[e].events)||(s=Wr("NON_CONFORMING_NAMESPACES",`${i} namespaces events don't satisfy namespace events for ${e}`)):s=Wr("NON_CONFORMING_NAMESPACES",`${i} namespaces methods don't satisfy namespace methods for ${e}`))})),s}function gn(e){return[...new Set(e.map((e=>e.includes(":")?e.split(":")[0]:e)))]}function fn(){const e=Er();return new Promise((t=>{switch(e){case mr.browser:t(function(){var e;return _r()&&(null===(e=navigator)||void 0===e?void 0:e.onLine)}());break;case mr.reactNative:t(async function(){var e;return!(br()&&typeof global<"u"&&null!=global&&global.NetInfo)||(null===(e=await(null==global?void 0:global.NetInfo.fetch()))||void 0===e?void 0:e.isConnected)}());break;case mr.node:default:t(!0)}}))}function yn(e){switch(Er()){case mr.browser:!function(e){_r()&&(window.addEventListener("online",(()=>e(!0))),window.addEventListener("offline",(()=>e(!1))))}(e);break;case mr.reactNative:!function(e){var t;br()&&typeof global<"u"&&null!=global&&global.NetInfo&&(null===(t=global)||void 0===t||t.NetInfo.addEventListener((t=>e(null===t||void 0===t?void 0:t.isConnected))))}(e)}}const mn={};let wn=class{static get(e){return mn[e]}static set(e,t){mn[e]=t}static delete(e){delete mn[e]}};const vn="PARSE_ERROR",bn="INVALID_REQUEST",_n="METHOD_NOT_FOUND",En="INVALID_PARAMS",Sn="INTERNAL_ERROR",In="SERVER_ERROR",On=[-32700,-32600,-32601,-32602,-32603],Nn={[vn]:{code:-32700,message:"Parse error"},[bn]:{code:-32600,message:"Invalid Request"},[_n]:{code:-32601,message:"Method not found"},[En]:{code:-32602,message:"Invalid params"},[Sn]:{code:-32603,message:"Internal error"},[In]:{code:-32e3,message:"Server error"}},Pn=In;function Rn(e){return Object.keys(Nn).includes(e)?Nn[e]:Nn[Pn]}var Tn,xn={},An={};var Cn,Ln={};function Un(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:3;
2return Date.now()*Math.pow(10,e)+Math.floor(Math.random()*Math.pow(10,e))}function Mn(){return BigInt(Un(arguments.length>0&&void 0!==arguments[0]?arguments[0]:6))}function Dn(e,t,i){return{id:i||Un(),jsonrpc:"2.0",method:e,params:t}}function jn(e,t){return{id:e,jsonrpc:"2.0",result:t}}function kn(e,t,i){return{id:e,jsonrpc:"2.0",error:zn(t,i)}}function zn(e,t){return typeof e>"u"?Rn(Sn):("string"==typeof e&&(e=Object.assign(Object.assign({},Rn(In)),{message:e})),typeof t<"u"&&(e.data=t),function(e){return On.includes(e)}(e.code)&&(e=function(e){return Object.values(Nn).find((t=>t.code===e))||Nn[Pn]}(e.code)),e)}!function(e){Object.defineProperty(e,"__esModule",{value:!0});const t=T;t.__exportStar(function(){if(Tn)return An;function e(){return(null===r.c||void 0===r.c?void 0:r.c.crypto)||(null===r.c||void 0===r.c?void 0:r.c.msCrypto)||{}}function t(){const t=e();return t.subtle||t.webkitSubtle}return Tn=1,Object.defineProperty(An,"__esModule",{value:!0}),An.isBrowserCryptoAvailable=An.getSubtleCrypto=An.getBrowerCrypto=void 0,An.getBrowerCrypto=e,An.getSubtleCrypto=t,An.isBrowserCryptoAvailable=function(){return!!e()&&!!t()},An}(),e),t.__exportStar(function(){if(Cn)return Ln;function e(){return typeof document>"u"&&typeof navigator<"u"&&"ReactNative"===navigator.product}function t(){return typeof a<"u"&&typeof a.versions<"u"&&typeof a.versions.node<"u"}return Cn=1,Object.defineProperty(Ln,"__esModule",{value:!0}),Ln.isBrowser=Ln.isNode=Ln.isReactNative=void 0,Ln.isReactNative=e,Ln.isNode=t,Ln.isBrowser=function(){return!e()&&!t()},Ln}(),e)}(xn);class qn{}class $n extends qn{constructor(e){super()}}class Kn extends qn{constructor(){super()}}class Vn extends Kn{constructor(e){super()}}function Hn(e,t){const i=function(e){const t=e.match(new RegExp(/^\w+:/,"gi"));if(t&&t.length)return t[0]}(e);return!(typeof i>"u")&&new RegExp(t).test(i)}function Fn(e){return Hn(e,"^wss?:")}function Bn(e){return new RegExp("wss?://localhost(:d{2,5})?").test(e)}function Gn(e){return"object"==typeof e&&"id"in e&&"jsonrpc"in e&&"2.0"===e.jsonrpc}function Wn(e){return Gn(e)&&"method"in e}function Yn(e){return Gn(e)&&(Jn(e)||Qn(e))}function Jn(e){return"result"in e}function Qn(e){return"error"in e}class Xn extends Vn{constructor(e){super(e),this.events=new O.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]: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(Dn(e.method,e.params||[],e.id||Mn().toString()),t)}async requestStrict(e,t){return new Promise((async(i,s)=>{if(!this.connection.connected)try{await this.open()}catch(r){s(r)}this.events.on(`${e.id}`,(e=>{Qn(e)?s(e.error):i(e.result)}));try{await this.connection.send(e,t)}catch(r){s(r)}}))}setConnection(){return arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.connection}onPayload(e){this.events.emit("payload",e),Yn(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&3e3===e.code&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.connection;this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),"string"==typeof e&&(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 Zn=e=>e.split("?")[0],eo=typeof WebSocket<"u"?WebSocket:typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:require("ws");class to{constructor(e){if(this.url=e,this.events=new O.EventEmitter,this.registering=!1,!Fn(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(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.url;await this.register(e)}async close(){return new Promise(((e,t)=>{typeof this.socket>"u"?t(new Error("Connection already closed")):(this.socket.onclose=t=>{this.onClose(t),e()},this.socket.close())}))}async send(e,t){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(Ze(e))}catch(i){this.onError(e.id,i)}}register(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.url;if(!Fn(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const e=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=e||this.events.listenerCount("open")>=e)&&this.events.setMaxListeners(e+1),new Promise(((e,t)=>{this.events.once("register_error",(e=>{this.resetMaxListeners(),t(e)})),this.events.once("open",(()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return t(new Error("WebSocket connection is missing or invalid"));e(this.socket)}))}))}return this.url=e,this.registering=!0,new Promise(((t,i)=>{const s=xn.isReactNative()?void 0:{rejectUnauthorized:!Bn(e)},r=new eo(e,[],s);typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u"?r.onerror=e=>{const t=e;i(this.emitError(t.error))}:r.on("error",(e=>{i(this.emitError(e))})),r.onopen=()=>{this.onOpen(r),t(r)}}
2))}onOpen(e){e.onmessage=e=>this.onPayload(e),e.onclose=e=>this.onClose(e),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="string"==typeof e.data?Xe(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const i=this.parseError(t),s=kn(e,i.message||i.toString());this.events.emit("payload",s)}parseError(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.url;return function(e,t,i){return e.message.includes("getaddrinfo ENOTFOUND")||e.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${i} RPC url at ${t}`):e}(e,Zn(t),"WS")}resetMaxListeners(){this.events.getMaxListeners()>10&&this.events.setMaxListeners(10)}emitError(e){const t=this.parseError(new Error((null===e||void 0===e?void 0:e.message)||`WebSocket connection failed for host: ${Zn(this.url)}`));return this.events.emit("register_error",t),t}}var io={exports:{}};!function(e,t){var i="__lodash_hash_undefined__",s=1,n=2,o=9007199254740991,a="[object Arguments]",c="[object Array]",h="[object AsyncFunction]",l="[object Boolean]",u="[object Date]",d="[object Error]",p="[object Function]",g="[object GeneratorFunction]",f="[object Map]",y="[object Number]",m="[object Null]",w="[object Object]",v="[object Promise]",b="[object Proxy]",_="[object RegExp]",E="[object Set]",S="[object String]",I="[object Symbol]",O="[object Undefined]",N="[object WeakMap]",P="[object ArrayBuffer]",R="[object DataView]",T=/^\[object .+?Constructor\]$/,x=/^(?:0|[1-9]\d*)$/,A={};A["[object Float32Array]"]=A["[object Float64Array]"]=A["[object Int8Array]"]=A["[object Int16Array]"]=A["[object Int32Array]"]=A["[object Uint8Array]"]=A["[object Uint8ClampedArray]"]=A["[object Uint16Array]"]=A["[object Uint32Array]"]=!0,A[a]=A[c]=A[P]=A[l]=A[R]=A[u]=A[d]=A[p]=A[f]=A[y]=A[w]=A[_]=A[E]=A[S]=A[N]=!1;var C="object"==typeof r.c&&r.c&&r.c.Object===Object&&r.c,L="object"==typeof self&&self&&self.Object===Object&&self,U=C||L||Function("return this")(),M=t&&!t.nodeType&&t,D=M&&e&&!e.nodeType&&e,j=D&&D.exports===M,k=j&&C.process,z=function(){try{return k&&k.binding&&k.binding("util")}catch{}}(),q=z&&z.isTypedArray;function $(e,t){for(var i=-1,s=null==e?0:e.length;++i<s;)if(t(e[i],i,e))return!0;return!1}function K(e,t){return e.has(t)}function V(e){var t=-1,i=Array(e.size);return e.forEach((function(e,s){i[++t]=[s,e]})),i}function H(e){var t=-1,i=Array(e.size);return e.forEach((function(e){i[++t]=e})),i}var F,B,G=Array.prototype,W=Function.prototype,Y=Object.prototype,J=U["__core-js_shared__"],Q=W.toString,X=Y.hasOwnProperty,Z=function(){var e=/[^.]+$/.exec(J&&J.keys&&J.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}(),ee=Y.toString,te=RegExp("^"+Q.call(X).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),ie=j?U.Buffer:void 0,se=U.Symbol,re=U.Uint8Array,ne=Y.propertyIsEnumerable,oe=G.splice,ae=se?se.toStringTag:void 0,ce=Object.getOwnPropertySymbols,he=ie?ie.isBuffer:void 0,le=(F=Object.keys,B=Object,function(e){return F(B(e))}),ue=ze(U,"DataView"),de=ze(U,"Map"),pe=ze(U,"Promise"),ge=ze(U,"Set"),fe=ze(U,"WeakMap"),ye=ze(Object,"create"),me=Ve(ue),we=Ve(de),ve=Ve(pe),be=Ve(ge),_e=Ve(fe),Ee=se?se.prototype:void 0,Se=Ee?Ee.valueOf:void 0;function Ie(e){var t=-1,i=null==e?0:e.length;for(this.clear();++t<i;){var s=e[t];this.set(s[0],s[1])}}function Oe(e){var t=-1,i=null==e?0:e.length;for(this.clear();++t<i;){var s=e[t];this.set(s[0],s[1])}}function Ne(e){var t=-1,i=null==e?0:e.length;for(this.clear();++t<i;){var s=e[t];this.set(s[0],s[1])}}function Pe(e){var t=-1,i=null==e?0:e.length;for(this.__data__=new Ne;++t<i;)this.add(e[t])}function Re(e){var t=this.__data__=new Oe(e);this.size=t.size}function Te(e,t){var i=Be(e),s=!i&&Fe(e),r=!i&&!s&&Ge(e),n=!i&&!s&&!r&&Xe(e),o=i||s||r||n,a=o?function(e,t){for(var i=-1,s=Array(e);++i<e;)s[i]=t(i);return s}(e.length,String):[],c=a.length;for(var h in e)(t||X.call(e,h))&&(!o||!("length"==h||r&&("offset"==h||"parent"==h)||n&&("buffer"==h||"byteLength"==h||"byteOffset"==h)||Ke(h,c)))&&a.push(h);return a}function xe(e,t){for(var i=e.length;i--;)if(He(e[i][0],t))return i;return-1}function Ae(e){return null==e?void 0===e?O:m:ae&&ae in Object(e)?function(e){var t=X.call(e,ae),i=e[ae];try{e[ae]=void 0;var s=!0}catch{}var r=ee.call(e);return s&&(t?e[ae]=i:delete e[ae]),r}(e):function(e){return ee.call(e)}(e)}function Ce(e){return Qe(e)&&Ae(e)==a}function Le(e,t,i,r,o){return e===t||(null==e||null==t||!Qe(e)&&!Qe(t)?e!==e&&t!==t:function(e,t,i,r,o,h){var p=Be(e),g=Be(t),m=p?c:$e(e),v=g?c:$e(t),b=(m=m==a?w:m)==w,O=(v=v==a?w:v)==w,N=m==v;if(N&&Ge(e)){if(!Ge(t))return!1;p=!0,b=!1}if(N&&!b)return h||(h=new Re),p||Xe(e)?De(e,t,i,r,o,h):function(e,t,i,r,o,a,c){switch(i){case R:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case P:return!(e.byteLength!=t.byteLength||!a(new re(e),new re(t)));case l:case u:case y:return He(+e,+t);case d:return e.name==t.name&&e.message==t.message;case _:case S:return e==t+"";case f:var h=V;case E:var p=r&s;if(h||(h=H),e.size!=t.size&&!p)return!1;var g=c.get(e);if(g)return g==t;r|=n,c.set(e,t);var m=De(h(e),h(t),r,o,a,c);return c.delete(e),m;case I:if(Se)return Se.call(e)==Se.call(t)}return!1}(e,t,m,i,r,o,h);if(!(i&s)){var T=b&&X.call(e,"__wrapped__"),x=O&&X.call(t,"__wrapped__");
2if(T||x){var A=T?e.value():e,C=x?t.value():t;return h||(h=new Re),o(A,C,i,r,h)}}return!!N&&(h||(h=new Re),function(e,t,i,r,n,o){var a=i&s,c=je(e),h=c.length,l=je(t),u=l.length;if(h!=u&&!a)return!1;for(var d=h;d--;){var p=c[d];if(!(a?p in t:X.call(t,p)))return!1}var g=o.get(e);if(g&&o.get(t))return g==t;var f=!0;o.set(e,t),o.set(t,e);for(var y=a;++d<h;){var m=e[p=c[d]],w=t[p];if(r)var v=a?r(w,m,p,t,e,o):r(m,w,p,e,t,o);if(!(void 0===v?m===w||n(m,w,i,r,o):v)){f=!1;break}y||(y="constructor"==p)}if(f&&!y){var b=e.constructor,_=t.constructor;b!=_&&"constructor"in e&&"constructor"in t&&!("function"==typeof b&&b instanceof b&&"function"==typeof _&&_ instanceof _)&&(f=!1)}return o.delete(e),o.delete(t),f}(e,t,i,r,o,h))}(e,t,i,r,Le,o))}function Ue(e){return!(!Je(e)||function(e){return!!Z&&Z in e}(e))&&(We(e)?te:T).test(Ve(e))}function Me(e){if(!function(e){var t=e&&e.constructor,i="function"==typeof t&&t.prototype||Y;return e===i}(e))return le(e);var t=[];for(var i in Object(e))X.call(e,i)&&"constructor"!=i&&t.push(i);return t}function De(e,t,i,r,o,a){var c=i&s,h=e.length,l=t.length;if(h!=l&&!(c&&l>h))return!1;var u=a.get(e);if(u&&a.get(t))return u==t;var d=-1,p=!0,g=i&n?new Pe:void 0;for(a.set(e,t),a.set(t,e);++d<h;){var f=e[d],y=t[d];if(r)var m=c?r(y,f,d,t,e,a):r(f,y,d,e,t,a);if(void 0!==m){if(m)continue;p=!1;break}if(g){if(!$(t,(function(e,t){if(!K(g,t)&&(f===e||o(f,e,i,r,a)))return g.push(t)}))){p=!1;break}}else if(f!==y&&!o(f,y,i,r,a)){p=!1;break}}return a.delete(e),a.delete(t),p}function je(e){return function(e,t,i){var s=t(e);return Be(e)?s:function(e,t){for(var i=-1,s=t.length,r=e.length;++i<s;)e[r+i]=t[i];return e}(s,i(e))}(e,Ze,qe)}function ke(e,t){var i=e.__data__;return function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}(t)?i["string"==typeof t?"string":"hash"]:i.map}function ze(e,t){var i=function(e,t){return null===e||void 0===e?void 0:e[t]}(e,t);return Ue(i)?i:void 0}Ie.prototype.clear=function(){this.__data__=ye?ye(null):{},this.size=0},Ie.prototype.delete=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t},Ie.prototype.get=function(e){var t=this.__data__;if(ye){var s=t[e];return s===i?void 0:s}return X.call(t,e)?t[e]:void 0},Ie.prototype.has=function(e){var t=this.__data__;return ye?void 0!==t[e]:X.call(t,e)},Ie.prototype.set=function(e,t){var s=this.__data__;return this.size+=this.has(e)?0:1,s[e]=ye&&void 0===t?i:t,this},Oe.prototype.clear=function(){this.__data__=[],this.size=0},Oe.prototype.delete=function(e){var t=this.__data__,i=xe(t,e);return!(i<0)&&(i==t.length-1?t.pop():oe.call(t,i,1),--this.size,!0)},Oe.prototype.get=function(e){var t=this.__data__,i=xe(t,e);return i<0?void 0:t[i][1]},Oe.prototype.has=function(e){return xe(this.__data__,e)>-1},Oe.prototype.set=function(e,t){var i=this.__data__,s=xe(i,e);return s<0?(++this.size,i.push([e,t])):i[s][1]=t,this},Ne.prototype.clear=function(){this.size=0,this.__data__={hash:new Ie,map:new(de||Oe),string:new Ie}},Ne.prototype.delete=function(e){var t=ke(this,e).delete(e);return this.size-=t?1:0,t},Ne.prototype.get=function(e){return ke(this,e).get(e)},Ne.prototype.has=function(e){return ke(this,e).has(e)},Ne.prototype.set=function(e,t){var i=ke(this,e),s=i.size;return i.set(e,t),this.size+=i.size==s?0:1,this},Pe.prototype.add=Pe.prototype.push=function(e){return this.__data__.set(e,i),this},Pe.prototype.has=function(e){return this.__data__.has(e)},Re.prototype.clear=function(){this.__data__=new Oe,this.size=0},Re.prototype.delete=function(e){var t=this.__data__,i=t.delete(e);return this.size=t.size,i},Re.prototype.get=function(e){return this.__data__.get(e)},Re.prototype.has=function(e){return this.__data__.has(e)},Re.prototype.set=function(e,t){var i=this.__data__;if(i instanceof Oe){var s=i.__data__;if(!de||s.length<199)return s.push([e,t]),this.size=++i.size,this;i=this.__data__=new Ne(s)}return i.set(e,t),this.size=i.size,this};var qe=ce?function(e){return null==e?[]:(e=Object(e),function(e,t){for(var i=-1,s=null==e?0:e.length,r=0,n=[];++i<s;){var o=e[i];t(o,i,e)&&(n[r++]=o)}return n}
2(ce(e),(function(t){return ne.call(e,t)})))}:function(){return[]},$e=Ae;function Ke(e,t){var i;return!!(t=null!==(i=t)&&void 0!==i?i:o)&&("number"==typeof e||x.test(e))&&e>-1&&e%1==0&&e<t}function Ve(e){if(null!=e){try{return Q.call(e)}catch{}try{return e+""}catch{}}return""}function He(e,t){return e===t||e!==e&&t!==t}(ue&&$e(new ue(new ArrayBuffer(1)))!=R||de&&$e(new de)!=f||pe&&$e(pe.resolve())!=v||ge&&$e(new ge)!=E||fe&&$e(new fe)!=N)&&($e=function(e){var t=Ae(e),i=t==w?e.constructor:void 0,s=i?Ve(i):"";if(s)switch(s){case me:return R;case we:return f;case ve:return v;case be:return E;case _e:return N}return t});var Fe=Ce(function(){return arguments}())?Ce:function(e){return Qe(e)&&X.call(e,"callee")&&!ne.call(e,"callee")},Be=Array.isArray;var Ge=he||function(){return!1};function We(e){if(!Je(e))return!1;var t=Ae(e);return t==p||t==g||t==h||t==b}function Ye(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=o}function Je(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}function Qe(e){return null!=e&&"object"==typeof e}var Xe=q?function(e){return function(t){return e(t)}}(q):function(e){return Qe(e)&&Ye(e.length)&&!!A[Ae(e)]};function Ze(e){return function(e){return null!=e&&Ye(e.length)&&!We(e)}(e)?Te(e):Me(e)}e.exports=function(e,t){return Le(e,t)}}(io,io.exports);var so=io.exports;const ro=(0,r.e)(so);var no=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var i=new Uint8Array(256),s=0;s<i.length;s++)i[s]=255;for(var r=0;r<e.length;r++){var n=e.charAt(r),o=n.charCodeAt(0);if(255!==i[o])throw new TypeError(n+" is ambiguous");i[o]=r}var a=e.length,c=e.charAt(0),h=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function u(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;var t=0;if(" "!==e[t]){for(var s=0,r=0;e[t]===c;)s++,t++;for(var n=(e.length-t)*h+1>>>0,o=new Uint8Array(n);e[t];){var l=i[e.charCodeAt(t)];if(255===l)return;for(var u=0,d=n-1;(0!==l||u<r)&&-1!==d;d--,u++)l+=a*o[d]>>>0,o[d]=l%256>>>0,l=l/256>>>0;if(0!==l)throw new Error("Non-zero carry");r=u,t++}if(" "!==e[t]){for(var p=n-r;p!==n&&0===o[p];)p++;for(var g=new Uint8Array(s+(n-p)),f=s;p!==n;)g[f++]=o[p++];return g}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var i=0,s=0,r=0,n=t.length;r!==n&&0===t[r];)r++,i++;for(var o=(n-r)*l+1>>>0,h=new Uint8Array(o);r!==n;){for(var u=t[r],d=0,p=o-1;(0!==u||d<s)&&-1!==p;p--,d++)u+=256*h[p]>>>0,h[p]=u%a>>>0,u=u/a>>>0;if(0!==u)throw new Error("Non-zero carry");s=d,r++}for(var g=o-s;g!==o&&0===h[g];)g++;for(var f=c.repeat(i);g<o;++g)f+=e.charAt(h[g]);return f},decodeUnsafe:u,decode:function(e){var i=u(e);if(i)return i;throw new Error(`Non-${t} character`)}}},oo=no;const ao=e=>{if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")};let co=class{constructor(e,t,i){this.name=e,this.prefix=t,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},ho=class{constructor(e,t,i){if(this.name=e,this.prefix=t,void 0===t.codePointAt(0))throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=i}decode(e){if("string"==typeof e){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))}throw Error("Can only multibase decode strings")}or(e){return uo(this,e)}},lo=class{constructor(e){this.decoders=e}or(e){return uo(this,e)}decode(e){const t=e[0],i=this.decoders[t];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}
2, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};const uo=(e,t)=>new lo({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}});let po=class{constructor(e,t,i,s){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=s,this.encoder=new co(e,t,i),this.decoder=new ho(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const go=e=>{let{name:t,prefix:i,encode:s,decode:r}=e;return new po(t,i,s,r)},fo=e=>{let{prefix:t,name:i,alphabet:s}=e;const{encode:r,decode:n}=oo(s,i);return go({prefix:t,name:i,encode:r,decode:e=>ao(n(e))})},yo=e=>{let{name:t,prefix:i,bitsPerChar:s,alphabet:r}=e;return go({prefix:i,name:t,encode:e=>((e,t,i)=>{const s="="===t[t.length-1],r=(1<<i)-1;let n="",o=0,a=0;for(let c=0;c<e.length;++c)for(a=a<<8|e[c],o+=8;o>i;)o-=i,n+=t[r&a>>o];if(o&&(n+=t[r&a<<i-o]),s)for(;n.length*i&7;)n+="=";return n})(e,r,s),decode:e=>((e,t,i,s)=>{const r={};for(let l=0;l<t.length;++l)r[t[l]]=l;let n=e.length;for(;"="===e[n-1];)--n;const o=new Uint8Array(n*i/8|0);let a=0,c=0,h=0;for(let l=0;l<n;++l){const t=r[e[l]];if(void 0===t)throw new SyntaxError(`Non-${s} character`);c=c<<i|t,a+=i,a>=8&&(a-=8,o[h++]=255&c>>a)}if(a>=i||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o})(e,r,s,t)})},mo=go({prefix:"\0",name:"identity",encode:e=>(e=>(new TextDecoder).decode(e))(e),decode:e=>(e=>(new TextEncoder).encode(e))(e)});var wo=Object.freeze({__proto__:null,identity:mo});const vo=yo({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var bo=Object.freeze({__proto__:null,base2:vo});const _o=yo({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Eo=Object.freeze({__proto__:null,base8:_o});const So=fo({prefix:"9",name:"base10",alphabet:"0123456789"});var Io=Object.freeze({__proto__:null,base10:So});const Oo=yo({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),No=yo({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Po=Object.freeze({__proto__:null,base16:Oo,base16upper:No});const Ro=yo({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),To=yo({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),xo=yo({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ao=yo({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Co=yo({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Lo=yo({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Uo=yo({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Mo=yo({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Do=yo({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var jo=Object.freeze({__proto__:null,base32:Ro,base32upper:To,base32pad:xo,base32padupper:Ao,base32hex:Co,base32hexupper:Lo,base32hexpad:Uo,base32hexpadupper:Mo,base32z:Do});const ko=fo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),zo=fo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var qo=Object.freeze({__proto__:null,base36:ko,base36upper:zo});const $o=fo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Ko=fo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Vo=Object.freeze({__proto__:null,base58btc:$o,base58flickr:Ko});const Ho=yo({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Fo=yo({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Bo=yo({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Go=yo({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Wo=Object.freeze({__proto__:null,base64:Ho,base64pad:Fo,base64url:Bo,base64urlpad:Go});const Yo=Array.from("\ud83d\ude80\ud83e\ude90\u2604\ud83d\udef0\ud83c\udf0c\ud83c\udf11\ud83c\udf12\ud83c\udf13\ud83c\udf14\ud83c\udf15\ud83c\udf16\ud83c\udf17\ud83c\udf18\ud83c\udf0d\ud83c\udf0f\ud83c\udf0e\ud83d\udc09\u2600\ud83d\udcbb\ud83d\udda5\ud83d\udcbe\ud83d\udcbf\ud83d\ude02\u2764\ud83d\ude0d\ud83e\udd23\ud83d\ude0a\ud83d\ude4f\ud83d\udc95\ud83d\ude2d\ud83d\ude18\ud83d\udc4d\ud83d\ude05\ud83d\udc4f\ud83d\ude01\ud83d\udd25\ud83e\udd70\ud83d\udc94\ud83d\udc96\ud83d\udc99\ud83d\ude22\ud83e\udd14\ud83d\ude06\ud83d\ude44\ud83d\udcaa\ud83d\ude09\u263a\ud83d\udc4c\ud83e\udd17\ud83d\udc9c\ud83d\ude14\ud83d\ude0e\ud83d\ude07\ud83c\udf39\ud83e\udd26\ud83c\udf89\ud83d\udc9e\u270c\u2728\ud83e\udd37\ud83d\ude31\ud83d\ude0c\ud83c\udf38\ud83d\ude4c\ud83d\ude0b\ud83d\udc97\ud83d\udc9a\ud83d\ude0f\ud83d\udc9b\ud83d\ude42\ud83d\udc93\ud83e\udd29\ud83d\ude04\ud83d\ude00\ud83d\udda4\ud83d\ude03\ud83d\udcaf\ud83d\ude48\ud83d\udc47\ud83c\udfb6\ud83d\ude12\ud83e\udd2d\u2763\ud83d\ude1c\ud83d\udc8b\ud83d\udc40\ud83d\ude2a\ud83d\ude11\ud83d\udca5\ud83d\ude4b\ud83d\ude1e\ud83d\ude29\ud83d\ude21\ud83e\udd2a\ud83d\udc4a\ud83e\udd73\ud83d\ude25\ud83e\udd24\ud83d\udc49\ud83d\udc83\ud83d\ude33\u270b\ud83d\ude1a\ud83d\ude1d\ud83d\ude34\ud83c\udf1f\ud83d\ude2c\ud83d\ude43\ud83c\udf40\ud83c\udf37\ud83d\ude3b\ud83d\ude13\u2b50\u2705\ud83e\udd7a\ud83c\udf08\ud83d\ude08\ud83e\udd18\ud83d\udca6\u2714\ud83d\ude23\ud83c\udfc3\ud83d\udc90\u2639\ud83c\udf8a\ud83d\udc98\ud83d\ude20\u261d\ud83d\ude15\ud83c\udf3a\ud83c\udf82\ud83c\udf3b\ud83d\ude10\ud83d\udd95\ud83d\udc9d\ud83d\ude4a\ud83d\ude39\ud83d\udde3\ud83d\udcab\ud83d\udc80\ud83d\udc51\ud83c\udfb5\ud83e\udd1e\ud83d\ude1b\ud83d\udd34\ud83d\ude24\ud83c\udf3c\ud83d\ude2b\u26bd\ud83e\udd19\u2615\ud83c\udfc6\ud83e\udd2b\ud83d\udc48\ud83d\ude2e\ud83d\ude46\ud83c\udf7b\ud83c\udf43\ud83d\udc36\ud83d\udc81\ud83d\ude32\ud83c\udf3f\ud83e\udde1\ud83c\udf81\u26a1\ud83c\udf1e\ud83c\udf88\u274c\u270a\ud83d\udc4b\ud83d\ude30\ud83e\udd28\ud83d\ude36\ud83e\udd1d\ud83d\udeb6\ud83d\udcb0\ud83c\udf53\ud83d\udca2\ud83e\udd1f\ud83d\ude41\ud83d\udea8\ud83d\udca8\ud83e\udd2c\u2708\ud83c\udf80\ud83c\udf7a\ud83e\udd13\ud83d\ude19\ud83d\udc9f\ud83c\udf31\ud83d\ude16\ud83d\udc76\ud83e\udd74\u25b6\u27a1\u2753\ud83d\udc8e\ud83d\udcb8\u2b07\ud83d\ude28\ud83c\udf1a\ud83e\udd8b\ud83d\ude37\ud83d\udd7a\u26a0\ud83d\ude45\ud83d\ude1f\ud83d\ude35\ud83d\udc4e\ud83e\udd32\ud83e\udd20\ud83e\udd27\ud83d\udccc\ud83d\udd35\ud83d\udc85\ud83e\uddd0\ud83d\udc3e\ud83c\udf52\ud83d\ude17\ud83e\udd11\ud83c\udf0a\ud83e\udd2f\ud83d\udc37\u260e\ud83d\udca7\ud83d\ude2f\ud83d\udc86\ud83d\udc46\ud83c\udfa4\ud83d\ude47\ud83c\udf51\u2744\ud83c\udf34\ud83d\udca3\ud83d\udc38\ud83d\udc8c\ud83d\udccd\ud83e\udd40\ud83e\udd22\ud83d\udc45\ud83d\udca1\ud83d\udca9\ud83d\udc50\ud83d\udcf8\ud83d\udc7b\ud83e\udd10\ud83e\udd2e\ud83c\udfbc\ud83e\udd75\ud83d\udea9\ud83c\udf4e\ud83c\udf4a\ud83d\udc7c\ud83d\udc8d\ud83d\udce3\ud83e\udd42"),Jo=Yo.reduce(((e,t,i)=>(e[i]=t,e)),[]),Qo=Yo.reduce(((e,t,i)=>(e[t.codePointAt(0)]=i,e)),[]);const Xo=go({prefix:"\ud83d\ude80",name:"base256emoji",encode:function(e){return e.reduce(((e,t)=>e+=Jo[t]),"")},decode:function(e){const t=[];for(const i of e){const e=Qo[i.codePointAt(0)];if(void 0===e)throw new Error(`Non-base256emoji character: ${i}`);t.push(e)}return new Uint8Array(t)}});var Zo=Object.freeze({__proto__:null,base256emoji:Xo}),ea=function e(t,i,s){i=i||[];for(var r=s=s||0;t>=sa;)i[s++]=255&t|ta,t/=128;for(;t&ia;)i[s++]=255&t|ta,t>>>=7;return i[s]=0|t,e.bytes=s-r+1,i},ta=128,ia=-128,sa=Math.pow(2,31);var ra=function e(t,i){var s,r=0,n=0,o=i=i||0,a=t.length;do{if(o>=a)throw e.bytes=0,new RangeError("Could not decode varint");s=t[o++],r+=n<28?(s&oa)<<n:(s&oa)*Math.pow(2,n),n+=7}while(s>=na);return e.bytes=o-i,r},na=128,oa=127;var aa=Math.pow(2,7),ca=Math.pow(2,14),ha=Math.pow(2,21),la=Math.pow(2,28),ua=Math.pow(2,35),da=Math.pow(2,42),pa=Math.pow(2,49),ga=Math.pow(2,56),fa=Math.pow(2,63),ya={encode:ea,decode:ra,encodingLength:function(e){return e<aa?1:e<ca?2:e<ha?3:e<la?4:e<ua?5:e<da?6:e<pa?7:e<ga?8:e<fa?9:10}},ma=ya;const wa=function(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;return ma.encode(e,t,i),t},va=e=>ma.encodingLength(e),ba=(e,t)=>{const i=t.byteLength,s=va(e),r=s+va(i),n=new Uint8Array(r+i);return wa(e,n,0),wa(i,n,s),n.set(t,r),new _a(e,i,t,n)};
2let _a=class{constructor(e,t,i,s){this.code=e,this.size=t,this.digest=i,this.bytes=s}};const Ea=e=>{let{name:t,code:i,encode:s}=e;return new Sa(t,i,s)};let Sa=class{constructor(e,t,i){this.name=e,this.code=t,this.encode=i}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?ba(this.code,t):t.then((e=>ba(this.code,e)))}throw Error("Unknown type, must be binary type")}};const Ia=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),Oa=Ea({name:"sha2-256",code:18,encode:Ia("SHA-256")}),Na=Ea({name:"sha2-512",code:19,encode:Ia("SHA-512")});Object.freeze({__proto__:null,sha256:Oa,sha512:Na});const Pa=ao,Ra={code:0,name:"identity",encode:Pa,digest:e=>ba(0,Pa(e))};Object.freeze({__proto__:null,identity:Ra});new TextEncoder,new TextDecoder;const Ta={...wo,...bo,...Eo,...Io,...Po,...jo,...qo,...Vo,...Wo,...Zo};function xa(e){return null!=globalThis.Buffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function Aa(e,t,i,s){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:i},decoder:{decode:s}}}const Ca=Aa("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),La=Aa("ascii","a",(e=>{let t="a";for(let i=0;i<e.length;i++)t+=String.fromCharCode(e[i]);return t}),(e=>{const t=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return null!=globalThis.Buffer&&null!=globalThis.Buffer.allocUnsafe?xa(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}((e=e.substring(1)).length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t})),Ua={utf8:Ca,"utf-8":Ca,hex:Ta.base16,latin1:La,ascii:La,binary:La,...Ta};const Ma="core",Da=`wc@2:${Ma}:`,ja="error",ka={database:":memory:"},za="client_ed25519_seed",qa=W.ONE_DAY,$a=W.SIX_HOURS,Ka="wss://relay.walletconnect.com",Va="wss://relay.walletconnect.org",Ha="relayer_message",Fa="relayer_message_ack",Ba="relayer_connect",Ga="relayer_disconnect",Wa="relayer_error",Ya="relayer_connection_stalled",Ja="relayer_publish",Qa="payload",Xa="connect",Za="disconnect",ec="error",tc=W.ONE_SECOND,ic="subscription_created",sc="subscription_deleted",rc="subscription_sync",nc="subscription_resubscribed",oc=1e3*W.FIVE_SECONDS,ac={wc_pairingDelete:{req:{ttl:W.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:W.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:W.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:W.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:W.ONE_DAY,prompt:!1,tag:0},res:{ttl:W.ONE_DAY,prompt:!1,tag:0}}},cc="pairing_create",hc="pairing_expire",lc="pairing_delete",uc="pairing_ping",dc="history_created",pc="history_updated",gc="history_deleted",fc="history_sync",yc="expirer_created",mc="expirer_deleted",wc="expirer_expired",vc="expirer_sync",bc="verify-api",_c="https://verify.walletconnect.com",Ec="https://verify.walletconnect.org";let Sc=class{constructor(e,t){this.core=e,this.logger=t,this.keychain=new Map,this.name="keychain",this.version="0.3",this.initialized=!1,this.storagePrefix=Da,this.init=async()=>{if(!this.initialized){const e=await this.getKeyChain();typeof e<"u"&&(this.keychain=e),this.initialized=!0}},this.has=e=>(this.isInitialized(),this.keychain.has(e)),this.set=async(e,t)=>{this.isInitialized(),this.keychain.set(e,t),await this.persist()},this.get=e=>{this.isInitialized();const t=this.keychain.get(e);if(typeof t>"u"){const{message:t}=Wr("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t},this.del=async e=>{this.isInitialized(),this.keychain.delete(e),await this.persist()},this.core=e,this.logger=Le.generateChildLogger(t,this.name)}get context(){return Le.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Nr(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Pr(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=Wr("NOT_INITIALIZED",this.name);throw new Error(e)}}},Ic=class{constructor(e,t,i){this.core=e,this.logger=t,this.name="crypto",this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=e=>(this.isInitialized(),this.keychain.has(e)),this.getClientId=async()=>{this.isInitialized();return qi(Ki(await this.getClientSeed()).publicKey)},this.generateKeyPair=()=>{this.isInitialized();const e=function(){const e=ps.generateKeyPair();return{privateKey:ji(e.secretKey,Ws),publicKey:ji(e.publicKey,Ws)}}();return this.setPrivateKey(e.publicKey,e.privateKey)},this.signJWT=async e=>{this.isInitialized();const t=Ki(await this.getClientSeed()),i=sr();return await Vi(i,e,qa,t)},this.generateSharedKey=(e,t,i)=>{this.isInitialized();const s=function(e,t){const i=ps.sharedKey(ki(e,Ws),ki(t,Ws),!0);return ji(new us(ds.SHA256,i).expand(ir),Ws)}(this.getPrivateKey(e),t);return this.setSymKey(s,i)},this.setSymKey=async(e,t)=>{this.isInitialized();const i=t||function(e){return ji(ds.hash(ki(e,Ws)),Ws)}(e);return await this.keychain.set(i,e),i},this.deleteKeyPair=async e=>{this.isInitialized(),await this.keychain.del(e)},this.deleteSymKey=async e=>{this.isInitialized(),await this.keychain.del(e)},this.encode=async(e,t,i)=>{this.isInitialized();const s=cr(i),r=Ze(t);if(hr(s)){const t=s.senderPublicKey,i=s.receiverPublicKey;e=await this.generateSharedKey(t,i)}const n=this.getSymKey(e),{type:o,senderPublicKey:a}=s;return or({type:o,symKey:n,message:r,senderPublicKey:a})},this.decode=async(e,t,i)=>{this.isInitialized();const s=function(e,t){const i=ar(e);return cr({type:nr(i.type),senderPublicKey:typeof i.senderPublicKey<"u"?ji(i.senderPublicKey,Ws):void 0,receiverPublicKey:null===t||void 0===t?void 0:t.receiverPublicKey})}(t,i);if(hr(s)){const t=s.receiverPublicKey,i=s.senderPublicKey;e=await this.generateSharedKey(t,i)}try{const i=function(e){const t=new Hi.ChaCha20Poly1305(ki(e.symKey,Ws)),{sealed:i,iv:s}=ar(e.encoded),r=t.open(s,i);if(null===r)throw new Error("Failed to decrypt");return ji(r,Js)}({symKey:this.getSymKey(e),encoded:t});return Xe(i)}catch(r){this.logger.error(`Failed to decode message from topic: '${e}', clientId: '${await this.getClientId()}'`),this.logger.error(r)}},this.getPayloadType=e=>nr(ar(e).type),this.getPayloadSenderPublicKey=e=>{const t=ar(e);return t.senderPublicKey?ji(t.senderPublicKey,Ws):void 0},this.core=e,this.logger=Le.generateChildLogger(t,this.name),this.keychain=i||new Sc(this.core,this.logger)}get context(){return Le.getLoggerContext(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(za)}catch{e=sr(),await this.keychain.set(za,e)}return function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"utf8";const i=Ua[t];if(!i)throw new Error(`Unsupported encoding "${t}"`);return"utf8"!==t&&"utf-8"!==t||null==globalThis.Buffer||null==globalThis.Buffer.from?i.decoder.decode(`${i.prefix}${e}`):xa(globalThis.Buffer.from(e,"utf-8"))}(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=Wr("NOT_INITIALIZED",this.name);throw new Error(e)}}},Oc=class extends Ke{constructor(e,t){super(e,t),this.logger=e,this.core=t,this.messages=new Map,this.name="messages",this.version="0.3",this.initialized=!1,this.storagePrefix=Da,this.init=async()=>
2{if(!this.initialized){this.logger.trace("Initialized");try{const e=await this.getRelayerMessages();typeof e<"u"&&(this.messages=e),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}finally{this.initialized=!0}}},this.set=async(e,t)=>{this.isInitialized();const i=rr(t);let s=this.messages.get(e);return typeof s>"u"&&(s={}),typeof s[i]<"u"||(s[i]=t,this.messages.set(e,s),await this.persist()),i},this.get=e=>{this.isInitialized();let t=this.messages.get(e);return typeof t>"u"&&(t={}),t},this.has=(e,t)=>{this.isInitialized();return typeof this.get(e)[rr(t)]<"u"},this.del=async e=>{this.isInitialized(),this.messages.delete(e),await this.persist()},this.logger=Le.generateChildLogger(e,this.name),this.core=t}get context(){return Le.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,Nr(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Pr(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=Wr("NOT_INITIALIZED",this.name);throw new Error(e)}}},Nc=class extends Ve{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.events=new O.EventEmitter,this.name="publisher",this.queue=new Map,this.publishTimeout=W.toMiliseconds(W.TEN_SECONDS),this.needsTransportRestart=!1,this.publish=async(e,t,i)=>{var s;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:e,message:t,opts:i}});try{const n=(null===i||void 0===i?void 0:i.ttl)||$a,o=Mr(i),a=(null===i||void 0===i?void 0:i.prompt)||!1,c=(null===i||void 0===i?void 0:i.tag)||0,h=(null===i||void 0===i?void 0:i.id)||Mn().toString(),l={topic:e,message:t,opts:{ttl:n,relay:o,prompt:a,tag:c,id:h}},u=setTimeout((()=>this.queue.set(h,l)),this.publishTimeout);try{await await Tr(this.rpcPublish(e,t,n,o,a,c,h),this.publishTimeout,"Failed to publish payload, please try again."),this.removeRequestFromQueue(h),this.relayer.events.emit(Ja,l)}catch(r){if(this.logger.debug("Publishing Payload stalled"),this.needsTransportRestart=!0,null!=(s=null===i||void 0===i?void 0:i.internal)&&s.throwOnFailedPublish)throw this.removeRequestFromQueue(h),r;return}finally{clearTimeout(u)}this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:e,message:t,opts:i}})}catch(n){throw this.logger.debug("Failed to Publish Payload"),this.logger.error(n),n}},this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.relayer=e,this.logger=Le.generateChildLogger(t,this.name),this.registerEventListeners()}get context(){return Le.getLoggerContext(this.logger)}rpcPublish(e,t,i,s,r,n,o){var a,c,h,l;const u={method:Dr(s.protocol).publish,params:{topic:e,message:t,ttl:i,prompt:r,tag:n},id:o};return Xr(null==(a=u.params)?void 0:a.prompt)&&(null==(c=u.params)||delete c.prompt),Xr(null==(h=u.params)?void 0:h.tag)&&(null==(l=u.params)||delete l.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:u}),this.relayer.request(u)}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach((async e=>{const{topic:t,message:i,opts:s}=e;await this.publish(t,i,s)}))}registerEventListeners(){this.relayer.core.heartbeat.on(B.HEARTBEAT_EVENTS.pulse,(()=>{if(this.needsTransportRestart)return this.needsTransportRestart=!1,void this.relayer.events.emit(Ya);this.checkQueue()})),this.relayer.on(Fa,(e=>{this.removeRequestFromQueue(e.id.toString())}))}},Pc=class{constructor(){this.map=new Map,this.set=(e,t)=>{const i=this.get(e);this.exists(e,t)||this.map.set(e,[...i,t])},this.get=e=>this.map.get(e)||[],this.exists=(e,t)=>this.get(e).includes(t),this.delete=(e,t)=>
2{if(typeof t>"u")return void this.map.delete(e);if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,t))return;const s=i.filter((e=>e!==t));s.length?this.map.set(e,s):this.map.delete(e)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}};var Rc=Object.defineProperty,Tc=Object.defineProperties,xc=Object.getOwnPropertyDescriptors,Ac=Object.getOwnPropertySymbols,Cc=Object.prototype.hasOwnProperty,Lc=Object.prototype.propertyIsEnumerable,Uc=(e,t,i)=>t in e?Rc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,Mc=(e,t)=>{for(var i in t||(t={}))Cc.call(t,i)&&Uc(e,i,t[i]);if(Ac)for(var i of Ac(t))Lc.call(t,i)&&Uc(e,i,t[i]);return e},Dc=(e,t)=>Tc(e,xc(t));let jc=class extends Be{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.subscriptions=new Map,this.topicMap=new Pc,this.events=new O.EventEmitter,this.name="subscription",this.version="0.3",this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=Da,this.subscribeTimeout=1e4,this.restartInProgress=!1,this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),this.clientId=await this.relayer.core.crypto.getClientId())},this.subscribe=async(e,t)=>{await this.restartToComplete(),this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:e,opts:t}});try{const i=Mr(t),s={topic:e,relay:i};this.pending.set(e,s);const r=await this.rpcSubscribe(e,i);return this.onSubscribe(r,s),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:e,opts:t}}),r}catch(i){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(i),i}},this.unsubscribe=async(e,t)=>{await this.restartToComplete(),this.isInitialized(),typeof(null===t||void 0===t?void 0:t.id)<"u"?await this.unsubscribeById(e,t.id,t):await this.unsubscribeByTopic(e,t)},this.isSubscribed=async e=>!!this.topics.includes(e)||await new Promise(((t,i)=>{const s=new W.Watch;s.start(this.pendingSubscriptionWatchLabel);const r=setInterval((()=>{!this.pending.has(e)&&this.topics.includes(e)&&(clearInterval(r),s.stop(this.pendingSubscriptionWatchLabel),t(!0)),s.elapsed(this.pendingSubscriptionWatchLabel)>=oc&&(clearInterval(r),s.stop(this.pendingSubscriptionWatchLabel),i(new Error("Subscription resolution timeout")))}),this.pollingInterval)})).catch((()=>!1)),this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=Le.generateChildLogger(t,this.name),this.clientId=""}get context(){return Le.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+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}hasSubscription(e,t){let i=!1;try{i=this.getSubscription(e).topic===t}catch{}return i}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const i=this.topicMap.get(e);await Promise.all(i.map((async i=>await this.unsubscribeById(e,i,t))))}async unsubscribeById(e,t,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}});try{const s=Mr(i);await this.rpcUnsubscribe(e,t,s);const r=Yr("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,r),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}})}catch(s){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(s),s}}async rpcSubscribe(e,t){const i={method:Dr(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{await await Tr(this.relayer.request(i),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Ya)}return rr(e+this.clientId)}async rpcBatchSubscribe(e){if(!e.length)return;const t={method:Dr(e[0].relay.protocol).batchSubscribe,params:{topics:e.map((e=>e.topic))}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:t});try{return await await Tr(this.relayer.request(t),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Payload stalled"),this.relayer.events.emit(Ya)}}rpcUnsubscribe(e,t,i){const s={method:Dr(i.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s}),this.relayer.request(s)}onSubscribe(e,t){this.setSubscription(e,Dc(Mc({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach((e=>{this.setSubscription(e.id,Mc({},e)),this.pending.delete(e.topic)}))}async onUnsubscribe(e,t,i){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,i),await this.relayer.messages.del(e)}
2async 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.subscriptions.has(e)||(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,Mc({},t)),this.topicMap.set(t.topic,e),this.events.emit(ic,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:t}=Wr("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(sc,Dc(Mc({},i),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(rc)}async reset(){if(this.cached.length){const e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let t=0;t<e;t++){const e=this.cached.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(e)}}this.events.emit(nc)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:e}=Wr("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(e)}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){if(!e.length)return;const t=await this.rpcBatchSubscribe(e);Jr(t)&&this.onBatchSubscribe(t.map(((t,i)=>Dc(Mc({},e[i]),{id:t}))))}async onConnect(){this.restartInProgress||(await this.restart(),this.onEnable())}onDisconnect(){this.onDisable()}async checkPending(){if(!this.initialized||this.relayer.transportExplicitlyClosed)return;const e=[];this.pending.forEach((t=>{e.push(t)})),await this.batchSubscribe(e)}registerEventListeners(){this.relayer.core.heartbeat.on(B.HEARTBEAT_EVENTS.pulse,(async()=>{await this.checkPending()})),this.relayer.on(Ba,(async()=>{await this.onConnect()})),this.relayer.on(Ga,(()=>{this.onDisconnect()})),this.events.on(ic,(async e=>{const t=ic;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()})),this.events.on(sc,(async e=>{const t=sc;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()}))}isInitialized(){if(!this.initialized){const{message:e}=Wr("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){this.restartInProgress&&await new Promise((e=>{const t=setInterval((()=>{this.restartInProgress||(clearInterval(t),e())}),this.pollingInterval)}))}};var kc=Object.defineProperty,zc=Object.getOwnPropertySymbols,qc=Object.prototype.hasOwnProperty,$c=Object.prototype.propertyIsEnumerable,Kc=(e,t,i)=>t in e?kc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i;let Vc=class extends He{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new O.EventEmitter,this.name="relayer",this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.connectionStatusPollingInterval=20,this.staleConnectionErrors=["socket hang up","socket stalled"],this.hasExperiencedNetworkDisruption=!1,this.request=async e=>{this.logger.debug("Publishing Request Payload");try{return await this.toEstablishConnection(),await this.provider.request(e)}catch(t){throw this.logger.debug("Failed to Publish Request"),this.logger.error(t),t}},this.onPayloadHandler=e=>{this.onProviderPayload(e)},this.onConnectHandler=()=>{this.events.emit(Ba)},this.onDisconnectHandler=()=>{this.onProviderDisconnect()},this.onProviderErrorHandler=e=>{this.logger.error(e),this.events.emit(Wa,e),this.logger.info("Fatal socket error received, closing transport"),this.transportClose()},this.registerProviderListeners=()=>{this.provider.on(Qa,this.onPayloadHandler),this.provider.on(Xa,this.onConnectHandler),this.provider.on(Za,this.onDisconnectHandler),this.provider.on(ec,this.onProviderErrorHandler)},this.core=e.core,this.logger=typeof e.logger<"u"&&"string"!=typeof e.logger?Le.generateChildLogger(e.logger,this.name):Le.pino(Le.getDefaultLoggerOptions({level:e.logger||"error"})),this.messages=new Oc(this.logger,e.core),this.subscriber=new jc(this,this.logger),this.publisher=new Nc(this,this.logger),this.relayUrl=(null===e||void 0===e?void 0:e.relayUrl)||Ka,this.projectId=e.projectId,this.provider={}}
2async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await this.createProvider(),await Promise.all([this.messages.init(),this.subscriber.init()]);try{await this.transportOpen()}catch{this.logger.warn(`Connection via ${this.relayUrl} failed, attempting to connect via failover domain ${Va}...`),await this.restartTransport(Va)}this.initialized=!0,setTimeout((async()=>{0===this.subscriber.topics.length&&(this.logger.info("No topics subscribed to after init, closing transport"),await this.transportClose(),this.transportExplicitlyClosed=!1)}),1e4)}get context(){return Le.getLoggerContext(this.logger)}get connected(){return this.provider.connection.connected}get connecting(){return this.provider.connection.connecting}async publish(e,t,i){this.isInitialized(),await this.publisher.publish(e,t,i),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now()})}async subscribe(e,t){var i;this.isInitialized();let s=(null==(i=this.subscriber.topicMap.get(e))?void 0:i[0])||"";return s||(await Promise.all([new Promise((t=>{this.subscriber.once(ic,(i=>{i.topic===e&&t()}))})),new Promise((async i=>{s=await this.subscriber.subscribe(e,t),i()}))]),s)}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 transportClose(){this.transportExplicitlyClosed=!0,this.hasExperiencedNetworkDisruption&&this.connected?await Tr(this.provider.disconnect(),1e3,"provider.disconnect()").catch((()=>this.onProviderDisconnect())):this.connected&&await this.provider.disconnect()}async transportOpen(e){if(this.transportExplicitlyClosed=!1,await this.confirmOnlineStateOrThrow(),!this.connectionAttemptInProgress){e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportClose(),await this.createProvider()),this.connectionAttemptInProgress=!0;try{await Promise.all([new Promise((e=>{if(!this.initialized)return e();this.subscriber.once(nc,(()=>{e()}))})),new Promise((async(e,t)=>{try{await Tr(this.provider.connect(),1e4,`Socket stalled when trying to connect to ${this.relayUrl}`)}catch(i){return void t(i)}e()}))])}catch(t){this.logger.error(t);const e=t;if(!this.isConnectionStalled(e.message))throw t;this.provider.events.emit(Za)}finally{this.connectionAttemptInProgress=!1,this.hasExperiencedNetworkDisruption=!1}}}async restartTransport(e){await this.confirmOnlineStateOrThrow(),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.transportClose(),await this.createProvider(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await fn())throw new Error("No internet connection detected. Please restart your network and try again.")}isConnectionStalled(e){return this.staleConnectionErrors.some((t=>e.includes(t)))}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Xn(new to(Ir({sdkVersion:"2.10.1",protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0}))),this.registerProviderListeners()}async recordMessageEvent(e){const{topic:t,message:i}=e;await this.messages.set(t,i)}async shouldIgnoreMessageEvent(e){const{topic:t,message:i}=e;if(!i||0===i.length)return this.logger.debug(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isSubscribed(t))return this.logger.debug(`Ignoring message for non-subscribed topic ${t}`),!0;const s=this.messages.has(t,i);return s&&this.logger.debug(`Ignoring duplicate message: ${i}`),s}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Wn(e)){if(!e.method.endsWith("_subscription"))return;const t=e.params,{topic:i,message:s,publishedAt:r}=t.data,n={topic:i,message:s,publishedAt:r};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(((e,t)=>{for(var i in t||(t={}))qc.call(t,i)&&Kc(e,i,t[i]);if(zc)for(var i of zc(t))$c.call(t,i)&&Kc(e,i,t[i]);return e})({type:"event",event:t.id},n)),this.events.emit(t.id,n),await this.acknowledgePayload(e),await this.onMessageEvent(n)}else Yn(e)&&this.events.emit(Fa,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(Ha,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const t=jn(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(Qa,this.onPayloadHandler),this.provider.off(Xa,this.onConnectHandler),this.provider.off(Za,this.onDisconnectHandler),this.provider.off(ec,this.onProviderErrorHandler)}async registerEventListeners(){this.events.on(Ya,(()=>{this.restartTransport().catch((e=>this.logger.error(e)))}));let e=await fn();yn((async t=>{this.initialized&&e!==t&&(e=t,t?await this.restartTransport().catch((e=>this.logger.error(e))):(this.hasExperiencedNetworkDisruption=!0,await this.transportClose().catch((e=>this.logger.error(e)))))}))}onProviderDisconnect(){this.events.emit(Ga),this.attemptToReconnect()}attemptToReconnect(){this.transportExplicitlyClosed||(this.logger.info("attemptToReconnect called. Connecting..."),setTimeout((async()=>{await this.restartTransport().catch((e=>this.logger.error(e)))}),W.toMiliseconds(tc)))}isInitialized(){if(!this.initialized){const{message:e}=Wr("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectionAttemptInProgress)return await new Promise((e=>{const t=setInterval((()=>{this.connected&&(clearInterval(t),e())}),this.connectionStatusPollingInterval)}));await this.restartTransport()}}};var Hc=Object.defineProperty,Fc=Object.getOwnPropertySymbols,Bc=Object.prototype.hasOwnProperty,Gc=Object.prototype.propertyIsEnumerable,Wc=(e,t,i)=>t in e?Hc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,Yc=(e,t)=>{for(var i in t||(t={}))Bc.call(t,i)&&Wc(e,i,t[i]);if(Fc)for(var i of Fc(t))Gc.call(t,i)&&Wc(e,i,t[i]);return e};let Jc=class extends Fe{constructor(e,t,i){let s=arguments.length>
23&&void 0!==arguments[3]?arguments[3]:Da,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:void 0;super(e,t,i,s),this.core=e,this.logger=t,this.name=i,this.map=new Map,this.version="0.3",this.cached=[],this.initialized=!1,this.storagePrefix=Da,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach((e=>{this.getKey&&null!==e&&!Xr(e)?this.map.set(this.getKey(e),e):function(e){var t;return null==(t=null===e||void 0===e?void 0:e.proposer)?void 0:t.publicKey}(e)?this.map.set(e.id,e):function(e){return null===e||void 0===e?void 0:e.topic}(e)&&this.map.set(e.topic,e)})),this.cached=[],this.initialized=!0)},this.set=async(e,t)=>{this.isInitialized(),this.map.has(e)?await this.update(e,t):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:e,value:t}),this.map.set(e,t),await this.persist())},this.get=e=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:e}),this.getData(e)),this.getAll=e=>(this.isInitialized(),e?this.values.filter((t=>Object.keys(e).every((i=>ro(t[i],e[i]))))):this.values),this.update=async(e,t)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:e,update:t});const i=Yc(Yc({},this.getData(e)),t);this.map.set(e,i),await this.persist()},this.delete=async(e,t)=>{this.isInitialized(),this.map.has(e)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:e,reason:t}),this.map.delete(e),await this.persist())},this.logger=Le.generateChildLogger(t,this.name),this.storagePrefix=s,this.getKey=r}get context(){return Le.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}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){const{message:t}=Wr("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(t),new Error(t)}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:e}=Wr("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}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}=Wr("NOT_INITIALIZED",this.name);throw new Error(e)}}},Qc=class{constructor(e,t){this.core=e,this.logger=t,this.name="pairing",this.version="0.3",this.events=new N,this.initialized=!1,this.storagePrefix=Da,this.ignoredPayloadTypes=[Xs],this.registeredMethods=[],this.init=async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))},this.register=e=>{let{methods:t}=e;this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...t])]},this.create=async()=>{this.isInitialized();const e=sr(),t=await this.core.crypto.setSymKey(e),i=Cr(W.FIVE_MINUTES),s={protocol:"irn"},r={topic:t,expiry:i,relay:s,active:!1},n=Hr({protocol:this.core.protocol,version:this.core.version,topic:t,symKey:e,relay:s});return await this.pairings.set(t,r),await this.core.relayer.subscribe(t),this.core.expirer.set(t,i),{topic:t,uri:n}},this.pair=async e=>{this.isInitialized(),this.isValidPair(e);const{topic:t,symKey:i,relay:s}=function(e){const t=e.indexOf(":"),i=-1!==e.indexOf("?")?e.indexOf("?"):void 0,s=e.substring(0,t),r=e.substring(t+1,i).split("@"),n=typeof i<"u"?e.substring(i):"",o=Ms.parse(n);return{protocol:s,topic:Vr(r[0]),version:parseInt(r[1],10),symKey:o.symKey,relay:Kr(o)}}(e.uri);let r;if(this.pairings.keys.includes(t)&&(r=this.pairings.get(t),r.active))throw new Error(`Pairing already exists: ${t}. Please try again with a new connection URI.`);this.core.crypto.keychain.has(t)||(await this.core.crypto.setSymKey(i,t),await this.core.relayer.subscribe(t,{relay:s}));const n=Cr(W.FIVE_MINUTES),o={topic:t,relay:s,expiry:n,active:!1};return await this.pairings.set(t,o),this.core.expirer.set(t,n),e.activatePairing&&await this.activate({topic:t}),this.events.emit(cc,o),o},this.activate=async e=>{let{topic:t}=e;this.isInitialized();const i=Cr(W.THIRTY_DAYS);await this.pairings.update(t,{active:!0,expiry:i}),this.core.expirer.set(t,i)},this.ping=async e=>{this.isInitialized(),await this.isValidPing(e);const{topic:t}=e;if(this.pairings.keys.includes(t)){const e=await this.sendRequest(t,"wc_pairingPing",{}),{done:i,resolve:s,reject:r}=Rr();this.events.once(Ur("pairing_ping",e),(e=>{let{error:t}=e;t?r(t):s()})),await i()}},this.updateExpiry=async e=>{let{topic:t,expiry:i}=e;this.isInitialized(),await this.pairings.update(t,{expiry:i})},this.updateMetadata=async e=>{let{topic:t,metadata:i}=e;this.isInitialized(),await this.pairings.update(t,{peerMetadata:i})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async e=>{this.isInitialized(),await this.isValidDisconnect(e);const{topic:t}=e;this.pairings.keys.includes(t)&&(await this.sendRequest(t,"wc_pairingDelete",Yr("USER_DISCONNECTED")),await this.deletePairing(t))},this.sendRequest=async(e,t,i)=>{const s=Dn(t,i),r=await this.core.crypto.encode(e,s),n=ac[t].req;return this.core.history.set(e,s),this.core.relayer.publish(e,r,n),s.id},this.sendResult=async(e,t,i)=>{const s=jn(e,i),r=await this.core.crypto.encode(t,s),n=await this.core.history.get(t,e),o=ac[n.request.method].res;await this.core.relayer.publish(t,r,o),await this.core.history.resolve(s)},this.sendError=async(e,t,i)=>{const s=kn(e,i),r=await this.core.crypto.encode(t,s),n=await this.core.history.get(t,e),o=ac[n.request.method]?ac[n.request.method].res:ac.unregistered_method.res;await this.core.relayer.publish(t,r,o),await this.core.history.resolve(s)},this.deletePairing=async(e,t)=>{await this.core.relayer.unsubscribe(e),await Promise.all([this.pairings.delete(e,Yr("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(e),t?Promise.resolve():this.core.expirer.del(e)])},this.cleanup=async()=>{const e=this.pairings.getAll().filter((e=>Lr(e.expiry)));await Promise.all(e.map((e=>this.deletePairing(e.topic))))},this.onRelayEventRequest=e=>{const{topic:t,payload:i}=e;switch(i.method){case"wc_pairingPing":return this.onPairingPingRequest(t,i);case"wc_pairingDelete":return this.onPairingDeleteRequest(t,i);default:return this.onUnknownRpcMethodRequest(t,i)}},this.onRelayEventResponse=async e=>{const{topic:t,payload:i}=e,s=(await this.core.history.get(t,i.id)).request.method;return"wc_pairingPing"===s?this.onPairingPingResponse(t,i):this.onUnknownRpcMethodResponse(s)},this.onPairingPingRequest=async(e,t)=>{const{id:i}=t;try{this.isValidPing({topic:e}),await this.sendResult(i,e,!0),this.events.emit(uc,{id:i,topic:e})}catch(s){await this.sendError(i,e,s),this.logger.error(s)}},this.onPairingPingResponse=(e,t)=>{const{id:i}=t;setTimeout((()=>{Jn(t)?this.events.emit(Ur("pairing_ping",i),{}):Qn(t)&&this.events.emit(Ur("pairing_ping",i),{error:t.error})}),500)},this.onPairingDeleteRequest=async(e,t)=>{const{id:i}=t;try{this.isValidDisconnect({topic:e}),await this.deletePairing(e),this.events.emit(lc,{id:i,topic:e})}catch(s){await this.sendError(i,e,s),this.logger.error(s)}},this.onUnknownRpcMethodRequest=async(e,t)=>{const{id:i,method:s}=t;try{if(this.registeredMethods.includes(s))return;const t=Yr("WC_METHOD_UNSUPPORTED",s);await this.sendError(i,e,t),this.logger.error(t)}catch(r){await this.sendError(i,e,r),this.logger.error(r)}},this.onUnknownRpcMethodResponse=e=>{this.registeredMethods.includes(e)||this.logger.error(Yr("WC_METHOD_UNSUPPORTED",e))},this.isValidPair=e=>{if(!hn(e)){const{message:t}=Wr("MISSING_OR_INVALID",`pair() params: ${e}`);throw new Error(t)}if(!function(e){if(Zr(e,!1))try{return typeof new URL(e)<"u"}catch{return!1}return!1}(e.uri)){const{message:t}=Wr("MISSING_OR_INVALID",`pair() uri: ${e.uri}`);throw new Error(t)}},this.isValidPing=async e=>
2{if(!hn(e)){const{message:t}=Wr("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidPairingTopic(t)},this.isValidDisconnect=async e=>{if(!hn(e)){const{message:t}=Wr("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidPairingTopic(t)},this.isValidPairingTopic=async e=>{if(!Zr(e,!1)){const{message:t}=Wr("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.pairings.keys.includes(e)){const{message:t}=Wr("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Lr(this.pairings.get(e).expiry)){await this.deletePairing(e);const{message:t}=Wr("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}},this.core=e,this.logger=Le.generateChildLogger(t,this.name),this.pairings=new Jc(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Le.getLoggerContext(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=Wr("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Ha,(async e=>{const{topic:t,message:i}=e;if(!this.pairings.keys.includes(t)||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))return;const s=await this.core.crypto.decode(t,i);try{Wn(s)?(this.core.history.set(t,s),this.onRelayEventRequest({topic:t,payload:s})):Yn(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:t,payload:s}),this.core.history.delete(t,s.id))}catch(r){this.logger.error(r)}}))}registerExpirerEvents(){this.core.expirer.on(wc,(async e=>{const{topic:t}=Ar(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(hc,{topic:t}))}))}},Xc=class extends $e{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.records=new Map,this.events=new O.EventEmitter,this.name="history",this.version="0.3",this.cached=[],this.initialized=!1,this.storagePrefix=Da,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach((e=>this.records.set(e.id,e))),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(e,t,i)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:e,request:t,chainId:i}),this.records.has(t.id))return;const s={id:t.id,topic:e,request:{method:t.method,params:t.params||null},chainId:i,expiry:Cr(W.THIRTY_DAYS)};this.records.set(s.id,s),this.events.emit(dc,s)},this.resolve=async e=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:e}),!this.records.has(e.id))return;const t=await this.getRecord(e.id);typeof t.response>"u"&&(t.response=Qn(e)?{error:e.error}:{result:e.result},this.records.set(t.id,t),this.events.emit(pc,t))},this.get=async(e,t)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:e,id:t}),await this.getRecord(t)),this.delete=(e,t)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:t}),this.values.forEach((i=>{if(i.topic===e){if(typeof t<"u"&&i.id!==t)return;this.records.delete(i.id),this.events.emit(gc,i)}}))},this.exists=async(e,t)=>(this.isInitialized(),!!this.records.has(t)&&(await this.getRecord(t)).topic===e),this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.logger=Le.generateChildLogger(t,this.name)}get context(){return Le.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach((t=>{if(typeof t.response<"u")return;const i={topic:t.topic,request:Dn(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(i)})),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const t=this.records.get(e);if(!t){const{message:t}=Wr("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(fc)}
2async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:e}=Wr("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}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(dc,(e=>{const t=dc;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e}),this.persist()})),this.events.on(pc,(e=>{const t=pc;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e}),this.persist()})),this.events.on(gc,(e=>{const t=gc;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e}),this.persist()})),this.core.heartbeat.on(B.HEARTBEAT_EVENTS.pulse,(()=>{this.cleanup()}))}cleanup(){try{this.records.forEach((e=>{W.toMiliseconds(e.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${e.id}`),this.delete(e.topic,e.id))}))}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=Wr("NOT_INITIALIZED",this.name);throw new Error(e)}}},Zc=class extends Ge{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.expirations=new Map,this.events=new O.EventEmitter,this.name="expirer",this.version="0.3",this.cached=[],this.initialized=!1,this.storagePrefix=Da,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach((e=>this.expirations.set(e.target,e))),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=e=>{try{const t=this.formatTarget(e);return typeof this.getExpiration(t)<"u"}catch{return!1}},this.set=(e,t)=>{this.isInitialized();const i=this.formatTarget(e),s={target:i,expiry:t};this.expirations.set(i,s),this.checkExpiry(i,s),this.events.emit(yc,{target:i,expiration:s})},this.get=e=>{this.isInitialized();const t=this.formatTarget(e);return this.getExpiration(t)},this.del=e=>{if(this.isInitialized(),this.has(e)){const t=this.formatTarget(e),i=this.getExpiration(t);this.expirations.delete(t),this.events.emit(mc,{target:t,expiration:i})}},this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.logger=Le.generateChildLogger(t,this.name)}get context(){return Le.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+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("string"==typeof e)return function(e){return xr("topic",e)}(e);if("number"==typeof e)return function(e){return xr("id",e)}(e);const{message:t}=Wr("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(vc)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:e}=Wr("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}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:t}=Wr("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(t),new Error(t)}return t}checkExpiry(e,t){const{expiry:i}=t;W.toMiliseconds(i)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(wc,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach(((e,t)=>this.checkExpiry(t,e)))}registerEventListeners(){this.core.heartbeat.on(B.HEARTBEAT_EVENTS.pulse,(()=>this.checkExpirations())),this.events.on(yc,(e=>{const t=yc;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})),this.events.on(wc,(e=>{const t=wc;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})),this.events.on(mc,(e=>{const t=mc;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}))}isInitialized(){if(!this.initialized){const{message:e}=Wr("NOT_INITIALIZED",this.name);throw new Error(e)}}},eh=class extends We{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,this.name=bc,this.initialized=!1,this.queue=[],this.verifyDisabled=!1,this.init=async e=>{if(this.verifyDisabled||br()||!_r())return;const t=(null===e||void 0===e?void 0:e.verifyUrl)||_c;this.verifyUrl!==t&&this.removeIframe(),this.verifyUrl=t;try{await this.createIframe()}catch(i){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(i)}if(!this.initialized){this.removeIframe(),this.verifyUrl=Ec;try{await this.createIframe()}catch(i){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(i),this.verifyDisabled=!0}}},this.register=async e=>{this.initialized?this.sendPost(e.attestationId):(this.addToQueue(e.attestationId),await this.init())},this.resolve=async e=>{if(this.isDevEnv)return"";const t=(null===e||void 0===e?void 0:e.verifyUrl)||_c;let i;try{i=await this.fetchAttestation(e.attestationId,t)}catch(s){this.logger.info(`failed to resolve attestation: ${e.attestationId} from url: ${t}`),this.logger.info(s),i=await this.fetchAttestation(e.attestationId,Ec)}return i},this.fetchAttestation=async(e,t)=>{this.logger.info(`resolving attestation: ${e} from url: ${t}`);const i=this.startAbortTimer(2*W.ONE_SECOND),s=await fetch(`${t}/attestation/${e}`,{signal:this.abortController.signal});return clearTimeout(i),200===s.status?await s.json():void 0},this.addToQueue=e=>{this.queue.push(e)},this.processQueue=()=>{0!==this.queue.length&&(this.queue.forEach((e=>this.sendPost(e))),this.queue=[])},this.sendPost=e=>{var t;try{if(!this.iframe)return;null==(t=this.iframe.contentWindow)||t.postMessage(e,"*"),this.logger.info(`postMessage sent: ${e} ${this.verifyUrl}`)}catch{}},this.createIframe=async()=>{let e;const t=i=>{"verify_ready"===i.data&&(this.initialized=!0,this.processQueue(),window.removeEventListener("message",t),e())};await Promise.race([new Promise((i=>{if(document.getElementById(bc))return i();window.addEventListener("message",t);const s=document.createElement("iframe");s.id=bc,s.src=`${this.verifyUrl}/${this.projectId}`,s.style.display="none",document.body.append(s),this.iframe=s,e=i})),new Promise(((e,i)=>setTimeout((()=>{window.removeEventListener("message",t),i("verify iframe load timeout")}),W.toMiliseconds(W.FIVE_SECONDS))))])},this.removeIframe=()=>{this.iframe&&(this.iframe.remove(),this.iframe=void 0,this.initialized=!1)},this.logger=Le.generateChildLogger(t,this.name),this.verifyUrl=_c,this.abortController=new AbortController,this.isDevEnv=vr()&&{NODE_ENV:"production",PUBLIC_URL:"",WDS_SOCKET_HOST:void 0,WDS_SOCKET_PATH:void 0,WDS_SOCKET_PORT:void 0,FAST_REFRESH:!0}.IS_VITEST}get context(){return Le.getLoggerContext(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout((()=>this.abortController.abort()),W.toMiliseconds(e))}};var th=Object.defineProperty,ih=Object.getOwnPropertySymbols,sh=Object.prototype.hasOwnProperty,rh=Object.prototype.propertyIsEnumerable,nh=(e,t,i)=>t in e?th(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,oh=(e,t)=>{for(var i in t||(t={}))sh.call(t,i)&&nh(e,i,t[i]);
2if(ih)for(var i of ih(t))rh.call(t,i)&&nh(e,i,t[i]);return e};const ah=class e extends qe{constructor(e){super(e),this.protocol="wc",this.version=2,this.name=Ma,this.events=new O.EventEmitter,this.initialized=!1,this.on=(e,t)=>this.events.on(e,t),this.once=(e,t)=>this.events.once(e,t),this.off=(e,t)=>this.events.off(e,t),this.removeListener=(e,t)=>this.events.removeListener(e,t),this.projectId=null===e||void 0===e?void 0:e.projectId,this.relayUrl=(null===e||void 0===e?void 0:e.relayUrl)||Ka;const t=typeof(null===e||void 0===e?void 0:e.logger)<"u"&&"string"!=typeof(null===e||void 0===e?void 0:e.logger)?e.logger:Le.pino(Le.getDefaultLoggerOptions({level:(null===e||void 0===e?void 0:e.logger)||ja}));this.logger=Le.generateChildLogger(t,this.name),this.heartbeat=new B.HeartBeat,this.crypto=new Ic(this,this.logger,null===e||void 0===e?void 0:e.keychain),this.history=new Xc(this,this.logger),this.expirer=new Zc(this,this.logger),this.storage=null!=e&&e.storage?e.storage:new F(oh(oh({},ka),null===e||void 0===e?void 0:e.storageOptions)),this.relayer=new Vc({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Qc(this,this.logger),this.verify=new eh(this.projectId||"",this.logger)}static async init(t){const i=new e(t);await i.initialize();const s=await i.crypto.getClientId();return await i.storage.setItem("WALLETCONNECT_CLIENT_ID",s),i}get context(){return Le.getLoggerContext(this.logger)}async start(){this.initialized||await this.initialize()}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.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}}},ch="client",hh=`wc@2:${ch}:`,lh=ch,uh="error",dh="WALLETCONNECT_DEEPLINK_CHOICE",ph=W.SEVEN_DAYS,gh={wc_sessionPropose:{req:{ttl:W.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:W.FIVE_MINUTES,prompt:!1,tag:1101}},wc_sessionSettle:{req:{ttl:W.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:W.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:W.ONE_DAY,prompt:!1,tag:1104},res:{ttl:W.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:W.ONE_DAY,prompt:!1,tag:1106},res:{ttl:W.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:W.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:W.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:W.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:W.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:W.ONE_DAY,prompt:!1,tag:1112},res:{ttl:W.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:W.THIRTY_SECONDS,prompt:!1,tag:1114},res:{ttl:W.THIRTY_SECONDS,prompt:!1,tag:1115}}},fh={min:W.FIVE_MINUTES,max:W.SEVEN_DAYS},yh="IDLE",mh="ACTIVE",wh=["wc_sessionPropose","wc_sessionRequest","wc_authRequest"];var vh=Object.defineProperty,bh=Object.defineProperties,_h=Object.getOwnPropertyDescriptors,Eh=Object.getOwnPropertySymbols,Sh=Object.prototype.hasOwnProperty,Ih=Object.prototype.propertyIsEnumerable,Oh=(e,t,i)=>t in e?vh(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,Nh=(e,t)=>{for(var i in t||(t={}))Sh.call(t,i)&&Oh(e,i,t[i]);if(Eh)for(var i of Eh(t))Ih.call(t,i)&&Oh(e,i,t[i]);return e},Ph=(e,t)=>bh(e,_h(t));let Rh=class extends Je{constructor(e){var t;super(e),t=this,this.name="engine",this.events=new N,this.initialized=!1,this.ignoredPayloadTypes=[Xs],this.requestQueue={state:yh,queue:[]},this.sessionRequestQueue={state:yh,queue:[]},this.requestQueueDelay=W.ONE_SECOND,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),this.client.core.pairing.register({methods:Object.keys(gh)}),this.initialized=!0,setTimeout((()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()}),W.toMiliseconds(this.requestQueueDelay)))},this.connect=async e=>{await this.isInitialized();const t=Ph(Nh({},e),{requiredNamespaces:e.requiredNamespaces||{},optionalNamespaces:e.optionalNamespaces||{}});await this.isValidConnect(t);const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:r,sessionProperties:n,relays:o}=t;let a,c=i,h=!1;if(c&&(h=this.client.core.pairing.pairings.get(c).active),!c||!h){const{topic:e,uri:t}=await this.client.core.pairing.create();c=e,a=t}const l=await this.client.core.crypto.generateKeyPair(),u=Nh({requiredNamespaces:s,optionalNamespaces:r,relays:null!==o&&void 0!==o?o:[{protocol:"irn"}],proposer:{publicKey:l,metadata:this.client.metadata}},n&&{sessionProperties:n}),{reject:d,resolve:p,done:g}=Rr(W.FIVE_MINUTES,"Proposal expired");if(this.events.once(Ur("session_connect"),(async e=>{let{error:t,session:i}=e;if(t)d(t);else if(i){i.self.publicKey=l;const e=Ph(Nh({},i),{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces});await this.client.session.set(i.topic,e),await this.setExpiry(i.topic,i.expiry),c&&await this.client.core.pairing.updateMetadata({topic:c,metadata:i.peer.metadata}),p(e)}})),!c){const{message:e}=Wr("NO_MATCHING_KEY",`connect() pairing topic: ${c}`);throw new Error(e)}const f=await this.sendRequest({topic:c,method:"wc_sessionPropose",params:u}),y=Cr(W.FIVE_MINUTES);return await this.setProposal(f,Nh({id:f,expiry:y},u)),{uri:a,approval:g}},this.pair=async e=>(await this.isInitialized(),await this.client.core.pairing.pair(e)),this.approve=async e=>{await this.isInitialized(),await this.isValidApprove(e);const{id:t,relayProtocol:i,namespaces:s,sessionProperties:r}=e,n=this.client.proposal.get(t);let{pairingTopic:o,proposer:a,requiredNamespaces:c,optionalNamespaces:h}=n;o=o||"",Qr(c)||(c=function(e,t){const i=an(e,t);if(i)throw new Error(i.message);const s={};for(const[r,n]of Object.entries(e))s[r]={methods:n.methods,events:n.events,chains:n.accounts.map((e=>`${e.split(":")[0]}:${e.split(":")[1]}`))};return s}(s,"approve()"));const l=await this.client.core.crypto.generateKeyPair(),u=a.publicKey,d=await this.client.core.crypto.generateSharedKey(l,u);o&&t&&(await this.client.core.pairing.updateMetadata({topic:o,metadata:a.metadata}),await this.sendResult({id:t,topic:o,result:{relay:{protocol:null!==i&&void 0!==i?i:"irn"},responderPublicKey:l}}),await this.client.proposal.delete(t,Yr("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:o}));const p=Nh({relay:{protocol:null!==i&&void 0!==i?i:"irn"},namespaces:s,requiredNamespaces:c,optionalNamespaces:h,pairingTopic:o,controller:{publicKey:l,metadata:this.client.metadata},expiry:Cr(ph)},r&&{sessionProperties:r});await this.client.core.relayer.subscribe(d),await this.sendRequest({topic:d,method:"wc_sessionSettle",params:p,throwOnFailedPublish:!0});const g=Ph(Nh({}
2,p),{topic:d,pairingTopic:o,acknowledged:!1,self:p.controller,peer:{publicKey:a.publicKey,metadata:a.metadata},controller:l});return await this.client.session.set(d,g),await this.setExpiry(d,Cr(ph)),{topic:d,acknowledged:()=>new Promise((e=>setTimeout((()=>e(this.client.session.get(d))),500)))}},this.reject=async e=>{await this.isInitialized(),await this.isValidReject(e);const{id:t,reason:i}=e,{pairingTopic:s}=this.client.proposal.get(t);s&&(await this.sendError(t,s,i),await this.client.proposal.delete(t,Yr("USER_DISCONNECTED")))},this.update=async e=>{await this.isInitialized(),await this.isValidUpdate(e);const{topic:t,namespaces:i}=e,s=await this.sendRequest({topic:t,method:"wc_sessionUpdate",params:{namespaces:i}}),{done:r,resolve:n,reject:o}=Rr();return this.events.once(Ur("session_update",s),(e=>{let{error:t}=e;t?o(t):n()})),await this.client.session.update(t,{namespaces:i}),{acknowledged:r}},this.extend=async e=>{await this.isInitialized(),await this.isValidExtend(e);const{topic:t}=e,i=await this.sendRequest({topic:t,method:"wc_sessionExtend",params:{}}),{done:s,resolve:r,reject:n}=Rr();return this.events.once(Ur("session_extend",i),(e=>{let{error:t}=e;t?n(t):r()})),await this.setExpiry(t,Cr(ph)),{acknowledged:s}},this.request=async e=>{await this.isInitialized(),await this.isValidRequest(e);const{chainId:t,request:i,topic:s,expiry:r}=e,n=Un(),{done:o,resolve:a,reject:c}=Rr(r);return this.events.once(Ur("session_request",n),(e=>{let{error:t,result:i}=e;t?c(t):a(i)})),await Promise.all([new Promise((async e=>{await this.sendRequest({clientRpcId:n,topic:s,method:"wc_sessionRequest",params:{request:i,chainId:t},expiry:r,throwOnFailedPublish:!0}).catch((e=>c(e))),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:t,id:n}),e()})),new Promise((async e=>{const i=await this.client.core.storage.getItem(dh);(async function(e){let{id:i,topic:s,wcDeepLink:r}=e;try{var n;if(!r)return;let e=null===(n="string"==typeof r?JSON.parse(r):r)||void 0===n?void 0:n.href;if("string"!=typeof e)return;e.endsWith("/")&&(e=e.slice(0,-1));const t=`${e}/wc?requestId=${i}&sessionTopic=${s}`,o=Er();o===mr.browser?t.startsWith("https://")?window.open(t,"_blank","noreferrer noopener"):window.open(t,"_self","noreferrer noopener"):o===mr.reactNative&&typeof(null==global?void 0:global.Linking)<"u"&&await global.Linking.openURL(t)}catch(t){console.error(t)}})({id:n,topic:s,wcDeepLink:i}),e()})),o()]).then((e=>e[2]))},this.respond=async e=>{await this.isInitialized(),await this.isValidRespond(e);const{topic:t,response:i}=e,{id:s}=i;Jn(i)?await this.sendResult({id:s,topic:t,result:i.result,throwOnFailedPublish:!0}):Qn(i)&&await this.sendError(s,t,i.error),this.cleanupAfterResponse(e)},this.ping=async e=>{await this.isInitialized(),await this.isValidPing(e);const{topic:t}=e;if(this.client.session.keys.includes(t)){const e=await this.sendRequest({topic:t,method:"wc_sessionPing",params:{}}),{done:i,resolve:s,reject:r}=Rr();this.events.once(Ur("session_ping",e),(e=>{let{error:t}=e;t?r(t):s()})),await i()}else this.client.core.pairing.pairings.keys.includes(t)&&await this.client.core.pairing.ping({topic:t})},this.emit=async e=>{await this.isInitialized(),await this.isValidEmit(e);const{topic:t,event:i,chainId:s}=e;await this.sendRequest({topic:t,method:"wc_sessionEvent",params:{event:i,
2chainId:s}})},this.disconnect=async e=>{await this.isInitialized(),await this.isValidDisconnect(e);const{topic:t}=e;this.client.session.keys.includes(t)?(await this.sendRequest({topic:t,method:"wc_sessionDelete",params:Yr("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession(t)):await this.client.core.pairing.disconnect({topic:t})},this.find=e=>(this.isInitialized(),this.client.session.getAll().filter((t=>function(e,t){const{requiredNamespaces:i}=t,s=Object.keys(e.namespaces),r=Object.keys(i);let n=!0;return!!Or(r,s)&&(s.forEach((t=>{const{accounts:s,methods:r,events:o}=e.namespaces[t],a=Fr(s),c=i[t];(!Or(Bs(t,c),a)||!Or(c.methods,r)||!Or(c.events,o))&&(n=!1)})),n)}(t,e)))),this.getPendingSessionRequests=()=>(this.isInitialized(),this.client.pendingRequest.getAll()),this.cleanupDuplicatePairings=async e=>{if(e.pairingTopic)try{const t=this.client.core.pairing.pairings.get(e.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter((i=>{var s,r;return(null==(s=i.peerMetadata)?void 0:s.url)&&(null==(r=i.peerMetadata)?void 0:r.url)===e.peer.metadata.url&&i.topic&&i.topic!==t.topic}));if(0===i.length)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map((e=>this.client.core.pairing.disconnect({topic:e.topic})))),this.client.logger.info("Duplicate pairings clean up finished")}catch(t){this.client.logger.error(t)}},this.deleteSession=async(e,t)=>{const{self:i}=this.client.session.get(e);await this.client.core.relayer.unsubscribe(e),this.client.session.delete(e,Yr("USER_DISCONNECTED")),this.client.core.crypto.keychain.has(i.publicKey)&&await this.client.core.crypto.deleteKeyPair(i.publicKey),this.client.core.crypto.keychain.has(e)&&await this.client.core.crypto.deleteSymKey(e),t||this.client.core.expirer.del(e),this.client.core.storage.removeItem(dh).catch((e=>this.client.logger.warn(e)))},this.deleteProposal=async(e,t)=>{await Promise.all([this.client.proposal.delete(e,Yr("USER_DISCONNECTED")),t?Promise.resolve():this.client.core.expirer.del(e)])},this.deletePendingSessionRequest=async function(e,i){let s=arguments.length>2&&void 0!==arguments[2]&&arguments[2];await Promise.all([t.client.pendingRequest.delete(e,i),s?Promise.resolve():t.client.core.expirer.del(e)]),t.sessionRequestQueue.queue=t.sessionRequestQueue.queue.filter((t=>t.id!==e)),s&&(t.sessionRequestQueue.state=yh)},this.setExpiry=async(e,t)=>{this.client.session.keys.includes(e)&&await this.client.session.update(e,{expiry:t}),this.client.core.expirer.set(e,t)},this.setProposal=async(e,t)=>{await this.client.proposal.set(e,t),this.client.core.expirer.set(e,t.expiry)},this.setPendingSessionRequest=async e=>{const t=gh.wc_sessionRequest.req.ttl,{id:i,topic:s,params:r,verifyContext:n}=e;await this.client.pendingRequest.set(i,{id:i,topic:s,params:r,verifyContext:n}),t&&this.client.core.expirer.set(i,Cr(t))},this.sendRequest=async e=>{const{topic:t,method:i,params:s,expiry:r,relayRpcId:n,clientRpcId:o,throwOnFailedPublish:a}=e,c=Dn(i,s,o);if(_r()&&wh.includes(i)){const e=rr(JSON.stringify(c));this.client.core.verify.register({attestationId:e})}const h=await this.client.core.crypto.encode(t,c),l=gh[i].req;return r&&(l.ttl=r),n&&(l.id=n),this.client.core.history.set(t,c),a?(l.internal=Ph(Nh({},l.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(t,h,l)):this.client.core.relayer.publish(t,h,l).catch((e=>this.client.logger.error(e))),c.id},this.sendResult=async e=>{const{id:t,topic:i,result:s,throwOnFailedPublish:r}=e,n=jn(t,s),o=await this.client.core.crypto.encode(i,n),a=await this.client.core.history.get(i,t),c=gh[a.request.method].res;r?(c.internal=Ph(Nh({},c.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,o,c)):this.client.core.relayer.publish(i,o,c).catch((e=>this.client.logger.error(e))),await this.client.core.history.resolve(n)},this.sendError=async(e,t,i)=>{const s=kn(e,i),r=await this.client.core.crypto.encode(t,s),n=await this.client.core.history.get(t,e),o=gh[n.request.method].res;this.client.core.relayer.publish(t,r,o),await this.client.core.history.resolve(s)},this.cleanup=async()=>{const e=[],t=[];
2this.client.session.getAll().forEach((t=>{Lr(t.expiry)&&e.push(t.topic)})),this.client.proposal.getAll().forEach((e=>{Lr(e.expiry)&&t.push(e.id)})),await Promise.all([...e.map((e=>this.deleteSession(e))),...t.map((e=>this.deleteProposal(e)))])},this.onRelayEventRequest=async e=>{this.requestQueue.queue.push(e),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state!==mh){for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=mh;const t=this.requestQueue.queue.shift();if(t)try{this.processRequest(t),await new Promise((e=>setTimeout(e,300)))}catch(e){this.client.logger.warn(e)}}this.requestQueue.state=yh}else this.client.logger.info("Request queue already active, skipping...")},this.processRequest=e=>{const{topic:t,payload:i}=e,s=i.method;switch(s){case"wc_sessionPropose":return this.onSessionProposeRequest(t,i);case"wc_sessionSettle":return this.onSessionSettleRequest(t,i);case"wc_sessionUpdate":return this.onSessionUpdateRequest(t,i);case"wc_sessionExtend":return this.onSessionExtendRequest(t,i);case"wc_sessionPing":return this.onSessionPingRequest(t,i);case"wc_sessionDelete":return this.onSessionDeleteRequest(t,i);case"wc_sessionRequest":return this.onSessionRequest(t,i);case"wc_sessionEvent":return this.onSessionEventRequest(t,i);default:return this.client.logger.info(`Unsupported request method ${s}`)}},this.onRelayEventResponse=async e=>{const{topic:t,payload:i}=e,s=(await this.client.core.history.get(t,i.id)).request.method;switch(s){case"wc_sessionPropose":return this.onSessionProposeResponse(t,i);case"wc_sessionSettle":return this.onSessionSettleResponse(t,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(t,i);case"wc_sessionExtend":return this.onSessionExtendResponse(t,i);case"wc_sessionPing":return this.onSessionPingResponse(t,i);case"wc_sessionRequest":return this.onSessionRequestResponse(t,i);default:return this.client.logger.info(`Unsupported response method ${s}`)}},this.onRelayEventUnknownPayload=e=>{const{topic:t}=e,{message:i}=Wr("MISSING_OR_INVALID",`Decoded payload on topic ${t} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)},this.onSessionProposeRequest=async(e,t)=>{const{params:i,id:s}=t;try{this.isValidConnect(Nh({},t.params));const r=Cr(W.FIVE_MINUTES),n=Nh({id:s,pairingTopic:e,expiry:r},i);await this.setProposal(s,n);const o=rr(JSON.stringify(t)),a=await this.getVerifyContext(o,n.proposer.metadata);this.client.events.emit("session_proposal",{id:s,params:n,verifyContext:a})}catch(r){await this.sendError(s,e,r),this.client.logger.error(r)}},this.onSessionProposeResponse=async(e,t)=>{const{id:i}=t;if(Jn(t)){const{result:s}=t;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:s});const r=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:r});const n=r.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:n});const o=s.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:o});const a=await this.client.core.crypto.generateSharedKey(n,o);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:a});const c=await this.client.core.relayer.subscribe(a);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:c}),await this.client.core.pairing.activate({topic:e})}else Qn(t)&&(await this.client.proposal.delete(i,Yr("USER_DISCONNECTED")),this.events.emit(Ur("session_connect"),{error:t.error}))},this.onSessionSettleRequest=async(e,t)=>{const{id:i,params:s}=t;try{this.isValidSessionSettleRequest(s);const{relay:i,controller:r,expiry:n,namespaces:o,requiredNamespaces:a,optionalNamespaces:c,sessionProperties:h,pairingTopic:l}=t.params,u=Nh({topic:e,relay:i,expiry:n,namespaces:o,acknowledged:!0,pairingTopic:l,requiredNamespaces:a,optionalNamespaces:c,controller:r.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:r.publicKey,metadata:r.metadata}},h&&{sessionProperties:h});
2await this.sendResult({id:t.id,topic:e,result:!0}),this.events.emit(Ur("session_connect"),{session:u}),this.cleanupDuplicatePairings(u)}catch(r){await this.sendError(i,e,r),this.client.logger.error(r)}},this.onSessionSettleResponse=async(e,t)=>{const{id:i}=t;Jn(t)?(await this.client.session.update(e,{acknowledged:!0}),this.events.emit(Ur("session_approve",i),{})):Qn(t)&&(await this.client.session.delete(e,Yr("USER_DISCONNECTED")),this.events.emit(Ur("session_approve",i),{error:t.error}))},this.onSessionUpdateRequest=async(e,t)=>{const{params:i,id:s}=t;try{const t=`${e}_session_update`,r=wn.get(t);if(r&&this.isRequestOutOfSync(r,s))return void this.client.logger.info(`Discarding out of sync request - ${s}`);this.isValidUpdate(Nh({topic:e},i)),await this.client.session.update(e,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:e,result:!0}),this.client.events.emit("session_update",{id:s,topic:e,params:i}),wn.set(t,s)}catch(r){await this.sendError(s,e,r),this.client.logger.error(r)}},this.isRequestOutOfSync=(e,t)=>parseInt(t.toString().slice(0,-3))<=parseInt(e.toString().slice(0,-3)),this.onSessionUpdateResponse=(e,t)=>{const{id:i}=t;Jn(t)?this.events.emit(Ur("session_update",i),{}):Qn(t)&&this.events.emit(Ur("session_update",i),{error:t.error})},this.onSessionExtendRequest=async(e,t)=>{const{id:i}=t;try{this.isValidExtend({topic:e}),await this.setExpiry(e,Cr(ph)),await this.sendResult({id:i,topic:e,result:!0}),this.client.events.emit("session_extend",{id:i,topic:e})}catch(s){await this.sendError(i,e,s),this.client.logger.error(s)}},this.onSessionExtendResponse=(e,t)=>{const{id:i}=t;Jn(t)?this.events.emit(Ur("session_extend",i),{}):Qn(t)&&this.events.emit(Ur("session_extend",i),{error:t.error})},this.onSessionPingRequest=async(e,t)=>{const{id:i}=t;try{this.isValidPing({topic:e}),await this.sendResult({id:i,topic:e,result:!0}),this.client.events.emit("session_ping",{id:i,topic:e})}catch(s){await this.sendError(i,e,s),this.client.logger.error(s)}},this.onSessionPingResponse=(e,t)=>{const{id:i}=t;setTimeout((()=>{Jn(t)?this.events.emit(Ur("session_ping",i),{}):Qn(t)&&this.events.emit(Ur("session_ping",i),{error:t.error})}),500)},this.onSessionDeleteRequest=async(e,t)=>{const{id:i}=t;try{this.isValidDisconnect({topic:e,reason:t.params}),await Promise.all([new Promise((t=>{this.client.core.relayer.once(Ja,(async()=>{t(await this.deleteSession(e))}))})),this.sendResult({id:i,topic:e,result:!0})]),this.client.events.emit("session_delete",{id:i,topic:e})}catch(s){this.client.logger.error(s)}},this.onSessionRequest=async(e,t)=>{const{id:i,params:s}=t;try{this.isValidRequest(Nh({topic:e},s));const t=rr(JSON.stringify(Dn("wc_sessionRequest",s,i))),r=this.client.session.get(e),n={id:i,topic:e,params:s,verifyContext:await this.getVerifyContext(t,r.peer.metadata)};await this.setPendingSessionRequest(n),this.addSessionRequestToSessionRequestQueue(n),this.processSessionRequestQueue()}catch(r){await this.sendError(i,e,r),this.client.logger.error(r)}},this.onSessionRequestResponse=(e,t)=>{const{id:i}=t;Jn(t)?this.events.emit(Ur("session_request",i),{result:t.result}):Qn(t)&&this.events.emit(Ur("session_request",i),{error:t.error})},this.onSessionEventRequest=async(e,t)=>{const{id:i,params:s}=t;try{const t=`${e}_session_event_${s.event.name}`,r=wn.get(t);if(r&&this.isRequestOutOfSync(r,i))return void this.client.logger.info(`Discarding out of sync request - ${i}`);this.isValidEmit(Nh({topic:e},s)),this.client.events.emit("session_event",{id:i,topic:e,params:s}),wn.set(t,i)}catch(r){await this.sendError(i,e,r),this.client.logger.error(r)}},this.addSessionRequestToSessionRequestQueue=e=>{this.sessionRequestQueue.queue.push(e)},this.cleanupAfterResponse=e=>{this.deletePendingSessionRequest(e.response.id,{message:"fulfilled",code:0}),setTimeout((()=>{this.sessionRequestQueue.state=yh,this.processSessionRequestQueue()}),W.toMiliseconds(this.requestQueueDelay))},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===mh)return void this.client.logger.info("session request queue is already active.");const e=this.sessionRequestQueue.queue[0];if(e)try{this.sessionRequestQueue.state=mh,this.client.events.emit("session_request",e)}catch(t){this.client.logger.error(t)}else this.client.logger.info("session request queue is empty.")}
2,this.onPairingCreated=e=>{if(e.active)return;const t=this.client.proposal.getAll().find((t=>t.pairingTopic===e.topic));t&&this.onSessionProposeRequest(e.topic,Dn("wc_sessionPropose",{requiredNamespaces:t.requiredNamespaces,optionalNamespaces:t.optionalNamespaces,relays:t.relays,proposer:t.proposer},t.id))},this.isValidConnect=async e=>{if(!hn(e)){const{message:t}=Wr("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(e)}`);throw new Error(t)}const{pairingTopic:t,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:r,relays:n}=e;if(Xr(t)||await this.isValidPairingTopic(t),!function(e,t){let i=!1;return t&&!e?i=!0:e&&Jr(e)&&e.length&&e.forEach((e=>{i=cn(e)})),i}(n,!0)){const{message:e}=Wr("MISSING_OR_INVALID",`connect() relays: ${n}`);throw new Error(e)}!Xr(i)&&0!==Qr(i)&&this.validateNamespaces(i,"requiredNamespaces"),!Xr(s)&&0!==Qr(s)&&this.validateNamespaces(s,"optionalNamespaces"),Xr(r)||this.validateSessionProps(r,"sessionProperties")},this.validateNamespaces=(e,t)=>{const i=function(e,t,i){let s=null;if(e&&Qr(e)){const r=on(e,t);r&&(s=r);const n=rn(e,t,i);n&&(s=n)}else s=Wr("MISSING_OR_INVALID",`${t}, ${i} should be an object with data`);return s}(e,"connect()",t);if(i)throw new Error(i.message)},this.isValidApprove=async e=>{if(!hn(e))throw new Error(Wr("MISSING_OR_INVALID",`approve() params: ${e}`).message);const{id:t,namespaces:i,relayProtocol:s,sessionProperties:r}=e;await this.isValidProposalId(t);const n=this.client.proposal.get(t),o=an(i,"approve()");if(o)throw new Error(o.message);const a=pn(n.requiredNamespaces,i,"approve()");if(a)throw new Error(a.message);if(!Zr(s,!0)){const{message:e}=Wr("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(e)}Xr(r)||this.validateSessionProps(r,"sessionProperties")},this.isValidReject=async e=>{if(!hn(e)){const{message:t}=Wr("MISSING_OR_INVALID",`reject() params: ${e}`);throw new Error(t)}const{id:t,reason:i}=e;if(await this.isValidProposalId(t),!function(e){return!(!e||"object"!=typeof e||!e.code||!en(e.code,!1)||!e.message||!Zr(e.message,!1))}(i)){const{message:e}=Wr("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(e)}},this.isValidSessionSettleRequest=e=>{if(!hn(e)){const{message:t}=Wr("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${e}`);throw new Error(t)}const{relay:t,controller:i,namespaces:s,expiry:r}=e;if(!cn(t)){const{message:e}=Wr("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(e)}const n=function(e,t){let i=null;return Zr(null===e||void 0===e?void 0:e.publicKey,!1)||(i=Wr("MISSING_OR_INVALID",`${t} controller public key should be a string`)),i}(i,"onSessionSettleRequest()");if(n)throw new Error(n.message);const o=an(s,"onSessionSettleRequest()");if(o)throw new Error(o.message);if(Lr(r)){const{message:e}=Wr("EXPIRED","onSessionSettleRequest()");throw new Error(e)}},this.isValidUpdate=async e=>{if(!hn(e)){const{message:t}=Wr("MISSING_OR_INVALID",`update() params: ${e}`);throw new Error(t)}const{topic:t,namespaces:i}=e;await this.isValidSessionTopic(t);const s=this.client.session.get(t),r=an(i,"update()");if(r)throw new Error(r.message);const n=pn(s.requiredNamespaces,i,"update()");if(n)throw new Error(n.message)},this.isValidExtend=async e=>{if(!hn(e)){const{message:t}=Wr("MISSING_OR_INVALID",`extend() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidSessionTopic(t)},this.isValidRequest=async e=>{if(!hn(e)){const{message:t}=Wr("MISSING_OR_INVALID",`request() params: ${e}`);throw new Error(t)}const{topic:t,request:i,chainId:s,expiry:r}=e;await this.isValidSessionTopic(t);const{namespaces:n}=this.client.session.get(t);if(!ln(n,s)){const{message:e}=Wr("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(e)}if(!function(e){return!(Xr(e)||!Zr(e.method,!1))}(i)){const{message:e}=Wr("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(e)}if(!un(n,s,i.method)){const{message:e}=Wr("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(e)}if(r&&!function(e,t){return en(e,!1)&&e<=t.max&&e>=t.min}(r,fh)){const{message:e}=Wr("MISSING_OR_INVALID",`request() expiry: ${r}
2. Expiry must be a number (in seconds) between ${fh.min} and ${fh.max}`);throw new Error(e)}},this.isValidRespond=async e=>{if(!hn(e)){const{message:t}=Wr("MISSING_OR_INVALID",`respond() params: ${e}`);throw new Error(t)}const{topic:t,response:i}=e;if(await this.isValidSessionTopic(t),!function(e){return!(Xr(e)||Xr(e.result)&&Xr(e.error)||!en(e.id,!1)||!Zr(e.jsonrpc,!1))}(i)){const{message:e}=Wr("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(i)}`);throw new Error(e)}},this.isValidPing=async e=>{if(!hn(e)){const{message:t}=Wr("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)},this.isValidEmit=async e=>{if(!hn(e)){const{message:t}=Wr("MISSING_OR_INVALID",`emit() params: ${e}`);throw new Error(t)}const{topic:t,event:i,chainId:s}=e;await this.isValidSessionTopic(t);const{namespaces:r}=this.client.session.get(t);if(!ln(r,s)){const{message:e}=Wr("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(e)}if(!function(e){return!(Xr(e)||!Zr(e.name,!1))}(i)){const{message:e}=Wr("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(e)}if(!dn(r,s,i.name)){const{message:e}=Wr("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(e)}},this.isValidDisconnect=async e=>{if(!hn(e)){const{message:t}=Wr("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)},this.getVerifyContext=async(e,t)=>{const i={verified:{verifyUrl:t.verifyUrl||_c,validation:"UNKNOWN",origin:t.url||""}};try{const s=await this.client.core.verify.resolve({attestationId:e,verifyUrl:t.verifyUrl});s&&(i.verified.origin=s.origin,i.verified.isScam=s.isScam,i.verified.validation=s.origin===new URL(t.url).origin?"VALID":"INVALID")}catch(s){this.client.logger.info(s)}return this.client.logger.info(`Verify context: ${JSON.stringify(i)}`),i},this.validateSessionProps=(e,t)=>{Object.values(e).forEach((e=>{if(!Zr(e,!1)){const{message:i}=Wr("MISSING_OR_INVALID",`${t} must be in Record<string, string> format. Received: ${JSON.stringify(e)}`);throw new Error(i)}}))}}async isInitialized(){if(!this.initialized){const{message:e}=Wr("NOT_INITIALIZED",this.name);throw new Error(e)}await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Ha,(async e=>{const{topic:t,message:i}=e;if(this.ignoredPayloadTypes.includes(this.client.core.crypto.getPayloadType(i)))return;const s=await this.client.core.crypto.decode(t,i);try{Wn(s)?(this.client.core.history.set(t,s),this.onRelayEventRequest({topic:t,payload:s})):Yn(s)?(await this.client.core.history.resolve(s),await this.onRelayEventResponse({topic:t,payload:s}),this.client.core.history.delete(t,s.id)):this.onRelayEventUnknownPayload({topic:t,payload:s})}catch(r){this.client.logger.error(r)}}))}registerExpirerEvents(){this.client.core.expirer.on(wc,(async e=>
2{const{topic:t,id:i}=Ar(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,Wr("EXPIRED"),!0);t?this.client.session.keys.includes(t)&&(await this.deleteSession(t,!0),this.client.events.emit("session_expire",{topic:t})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))}))}registerPairingEvents(){this.client.core.pairing.events.on(cc,(e=>this.onPairingCreated(e)))}isValidPairingTopic(e){if(!Zr(e,!1)){const{message:t}=Wr("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}=Wr("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Lr(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=Wr("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!Zr(e,!1)){const{message:t}=Wr("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(t)}if(!this.client.session.keys.includes(e)){const{message:t}=Wr("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(Lr(this.client.session.get(e).expiry)){await this.deleteSession(e);const{message:t}=Wr("EXPIRED",`session topic: ${e}`);throw new Error(t)}}async isValidSessionOrPairingTopic(e){if(this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else{if(!this.client.core.pairing.pairings.keys.includes(e)){if(Zr(e,!1)){const{message:t}=Wr("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}{const{message:t}=Wr("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}this.isValidPairingTopic(e)}}async isValidProposalId(e){if(!function(e){return"number"==typeof e}(e)){const{message:t}=Wr("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=Wr("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(Lr(this.client.proposal.get(e).expiry)){await this.deleteProposal(e);const{message:t}=Wr("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}},Th=class extends Jc{constructor(e,t){super(e,t,"proposal",hh),this.core=e,this.logger=t}},xh=class extends Jc{constructor(e,t){super(e,t,"session",hh),this.core=e,this.logger=t}},Ah=class extends Jc{constructor(e,t){super(e,t,"request",hh,(e=>e.id)),this.core=e,this.logger=t}},Ch=class e extends Ye{constructor(e){super(e),this.protocol="wc",this.version=2,this.name=lh,this.events=new O.EventEmitter,this.on=(e,t)=>this.events.on(e,t),this.once=(e,t)=>this.events.once(e,t),this.off=(e,t)=>this.events.off(e,t),this.removeListener=(e,t)=>this.events.removeListener(e,t),this.removeAllListeners=e=>this.events.removeAllListeners(e),this.connect=async e=>{try{return await this.engine.connect(e)}catch(t){throw this.logger.error(t.message),t}},this.pair=async e=>{try{return await this.engine.pair(e)}catch(t){throw this.logger.error(t.message),t}},this.approve=async e=>{try{return await this.engine.approve(e)}catch(t){throw this.logger.error(t.message),t}},this.reject=async e=>{try{return await this.engine.reject(e)}catch(t){throw this.logger.error(t.message),t}},this.update=async e=>{try{return await this.engine.update(e)}catch(t){throw this.logger.error(t.message),t}},this.extend=async e=>{try{return await this.engine.extend(e)}catch(t){throw this.logger.error(t.message),t}},this.request=async e=>{try{return await this.engine.request(e)}catch(t){throw this.logger.error(t.message),t}},this.respond=async e=>{try{return await this.engine.respond(e)}catch(t){throw this.logger.error(t.message),t}},this.ping=async e=>{try{return await this.engine.ping(e)}catch(t){throw this.logger.error(t.message),t}},this.emit=async e=>{try{return await this.engine.emit(e)}catch(t){throw this.logger.error(t.message),t}},this.disconnect=async e=>{try{return await this.engine.disconnect(e)}catch(t){throw this.logger.error(t.message),t}},this.find=e=>{try{return this.engine.find(e)}catch(t){throw this.logger.error(t.message),t}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(e){throw this.logger.error(e.message),e}},this.name=(null===e||void 0===e?void 0:e.name)||lh,this.metadata=(null===e||void 0===e?void 0:e.metadata)||Ls()||{name:"",description:"",url:"",icons:[""]};const t=typeof(null===e||void 0===e?void 0:e.logger)<"u"&&"string"!=typeof(null===e||void 0===e?void 0:e.logger)?e.logger:Le.pino(Le.getDefaultLoggerOptions({level:(null===e||void 0===e?void 0:e.logger)||uh}));this.core=(null===e||void 0===e?void 0:e.core)||new ah(e),this.logger=Le.generateChildLogger(t,this.name),this.session=new xh(this.core,this.logger),this.proposal=new Th(this.core,this.logger),this.pendingRequest=new Ah(this.core,this.logger),this.engine=new Rh(this)}static async init(t){const i=new e(t);return await i.initialize(),i}get context(){return Le.getLoggerContext(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.engine.init(),this.core.verify.init({verifyUrl:this.metadata.verifyUrl}),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};const Lh=(()=>{var e;const t=null===(e=Is())||void 0===e||null===(e=e.os)||void 0===e?void 0:e.toLowerCase();return null!==t&&void 0!==t&&t.includes("android")?"android":null!==t&&void 0!==t&&t.toLowerCase().includes("ios")||null!==t&&void 0!==t&&t.toLowerCase().includes("mac")&&navigator.maxTouchPoints>1?"ios":"desktop"})(),Uh={position:"fixed",top:"0",left:"0",right:"0",bottom:"0",backgroundColor:"rgba(0,0,0,0.8)",backdropFilter:"blur(10px)",zIndex:"9999",display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",color:"white",fontWeight:"500",fontFamily:"'Barlow', sans-serif"},Mh={width:"840px",height:"540px",zIndex:"99999",backgroundColor:"white",border:"none",outline:"none",borderRadius:"40px",boxShadow:"0px 4px 40px 0px rgb(0 0 0), 0px 4px 8px 0px rgb(0 0 0 / 25%)",position:"fixed",top:"50%",left:"50%",transform:"translate(-50%,-50%)"};const Dh=new class{constructor(){h(this,"bridgeUrl","https://login.argent.xyz"),h(this,"mobileUrl","argent://"),h(this,"type","overlay"),h(this,"wcUri"),h(this,"overlay"),h(this,"popupWindow"),h(this,"closingTimeout"),h(this,"close",(()=>{var e,t;null!==(e=this.overlay)&&void 0!==e&&e.remove(),null!==(t=this.popupWindow)&&void 0!==t&&t.close(),this.overlay=void 0,this.popupWindow=void 0}))}showConnectionModal(e){const t=encodeURIComponent(e),i=encodeURIComponent(window.location.href);this.showModal({desktop:`${this.bridgeUrl}?wc=${t}&device=desktop`,ios:`${this.mobileUrl}app/wc?uri=${t}&href=${i}&device=mobile`,android:`${this.mobileUrl}app/wc?uri=${t}&href=${i}&device=mobile`})}showApprovalModal(e){if("desktop"===Lh)return void this.showModal({desktop:`${this.bridgeUrl}?action=sign`,ios:"",android:""});const t=encodeURIComponent(window.location.href);this.showModal({desktop:`${this.bridgeUrl}?action=sign&device=desktop`,ios:`${this.mobileUrl}app/wc/request?href=${t}&device=mobile`,android:`${this.mobileUrl}app/wc/request?href=${t}&device=mobile`})}closeModal(e){var t,i;e?(null!==(t=this.overlay)&&void 0!==t&&null!==(t=t.querySelector("iframe"))&&void 0!==t&&null!==(t=t.contentWindow)&&void 0!==t&&t.postMessage("argent-login.success","*"),null!==(i=this.popupWindow)&&void 0!==i&&i.postMessage("argent-login.success","*"),this.closingTimeout=setTimeout(this.close,3400)):this.close()}showModal(e){if(clearTimeout(this.closingTimeout),(this.overlay||this.popupWindow)&&this.close(),"android"===Lh||"ios"===Lh){const t=document.createElement("button");return t.style.display="none",t.addEventListener("click",(()=>{window.location.href=e[Lh]})),void t.click()}if("window"===this.type){const t="menubar=no,location=no,resizable=no,scrollbars=no,status=no,width=840,height=540";return void(this.popupWindow=window.open(e.desktop,"_blank",t)||void 0)}const t=document.createElement("div");t.innerHTML='\n  <div id="argent-mobile-modal-container" style="position: relative">\n    <iframe class="argent-iframe" allow="clipboard-write"></iframe>\n    <div class="argent-close-button" style="position: absolute; top: 24px; right: 24px; cursor: pointer;">\n      <svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">\n        <circle cx="16" cy="16" r="16" fill="#F5F3F0"/>\n        <path fill-rule="evenodd" clip-rule="evenodd" d="M22.2462 9.75382C22.7018 10.2094 22.7018 10.9481 22.2462 11.4037L17.6499 16L22.2462 20.5963C22.7018 21.0519 22.7018 21.7906 22.2462 22.2462C2
21.7905 22.7018 21.0519 22.7018 20.5962 22.2462L16 17.6499L11.4039 22.246C10.9482 22.7017 10.2096 22.7017 9.75394 22.246C9.29833 21.7904 9.29833 21.0517 9.75394 20.5961L14.3501 16L9.75394 11.4039C9.29833 10.9483 9.29833 10.2096 9.75394 9.75396C10.2096 9.29835 10.9482 9.29835 11.4039 9.75396L16 14.3501L20.5962 9.75382C21.0519 9.29821 21.7905 9.29821 22.2462 9.75382Z" fill="#333332"/>\n      </svg>\n    </div>\n  </div>\n',t.id="argent-mobile-modal-overlay";for(const[s,r]of Object.entries(Uh))t.style[s]=r;document.body.appendChild(t),t.addEventListener("click",(()=>this.closeModal())),this.overlay=t;const i=t.querySelector("iframe");i.setAttribute("src",e.desktop);for(const[s,r]of Object.entries(Mh))i.style[s]=r;t.querySelector(".argent-close-button").addEventListener("click",(()=>this.closeModal()))}},jh=n.AA.NetworkName,kh=e=>{if(!e)throw new Error(`Unknown or unsupported chainId (${e}), either specify a supported chain or set bridgeUrl.`);const t=parseInt(`${e}`);return String(e).startsWith(jh.SN_SEPOLIA)||11155111===t?"https://login.hydrogen.argent47.net":String(e).startsWith(jh.SN_MAIN)||1===t?"https://login.argent.xyz":void 0},zh=e=>{if(!e)throw new Error(`Unknown or unsupported chainId (${e}), either specify a supported chain or set mobileUrl.`);const t=parseInt(`${e}`);return String(e).startsWith(jh.SN_SEPOLIA)||11155111===t?"argent-dev://":String(e).startsWith(jh.SN_MAIN)||1===t?"argent://":void 0};class qh extends me{constructor(e){super(),this.opts=e,this.protocol="wc",this.version=2}}class $h extends me{constructor(e,t){super(),this.core=e,this.logger=t,this.records=new Map}}class Kh{constructor(e,t){this.logger=e,this.core=t}}class Vh extends me{constructor(e,t){super(),this.relayer=e,this.logger=t}}let Hh=class extends me{constructor(e){super()}},Fh=class{constructor(e,t,i,s){this.core=e,this.logger=t,this.name=i}};class Bh extends me{constructor(e,t){super(),this.relayer=e,this.logger=t}}class Gh extends me{constructor(e,t){super(),this.core=e,this.logger=t}}class Wh{constructor(e,t){this.projectId=e,this.logger=t}}let Yh=class{constructor(e){this.opts=e,this.protocol="wc",this.version=2}},Jh=class{constructor(e){this.client=e}};const Qh=":";function Xh(e){const{namespace:t,reference:i}=function(e){const[t,i,s]=e.split(Qh);return{namespace:t,reference:i,address:s}}(e);return function(e){const{namespace:t,reference:i}=e;return[t,i].join(Qh)}({namespace:t,reference:i})}function Zh(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];const i=[];return Object.keys(e).forEach((s=>{if(t.length&&!t.includes(s))return;const r=e[s];i.push(...function(e){return function(e,t){const i=[];return e.forEach((e=>{const s=t(e);i.includes(s)||i.push(s)})),i}(e,Xh)}(r.accounts))})),i}function el(e,t){return e.includes(":")?[e]:t.chains||[]}const tl="base10",il="base16",sl="base64pad",rl="utf8",nl=0,ol=1,al=0,cl=1,hl=12,ll=32;function ul(){return ji(tt.randomBytes(ll),il)}function dl(e){return ji(ds.hash(ki(e,rl)),il)}function pl(e){return Number(ji(e,tl))}function gl(e){const t=function(e){return ki(`${e}`,tl)}(typeof e.type<"u"?e.type:nl);if(pl(t)===ol&&typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const i=typeof e.senderPublicKey<"u"?ki(e.senderPublicKey,il):void 0,s=typeof e.iv<"u"?ki(e.iv,il):tt.randomBytes(hl);return function(e){if(pl(e.type)===ol){if(typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return ji(kt([e.type,e.senderPublicKey,e.iv,e.sealed]),sl)}return ji(kt([e.type,e.iv,e.sealed]),sl)}({type:t,sealed:new Hi.ChaCha20Poly1305(ki(e.symKey,il)).seal(s,ki(e.message,rl)),iv:s,senderPublicKey:i})}function fl(e){const t=ki(e,sl),i=t.slice(al,cl),s=cl;if(pl(i)===ol){const e=s+ll,r=e+hl,n=t.slice(s,e),o=t.slice(e,r);return{type:i,sealed:t.slice(r),iv:o,senderPublicKey:n}}const r=s+hl,n=t.slice(s,r);return{type:i,sealed:t.slice(r),iv:n}}function yl(e){const t=(null===e||void 0===e?void 0:e.type)||nl;if(t===ol){if(typeof(null===e||void 0===e?void 0:e.senderPublicKey)>"u")throw new Error("missing sender public key");if(typeof(null===e||void 0===e?void 0:e.receiverPublicKey)>"u")throw new Error("missing receiver public key")}return{type:t,senderPublicKey:null===e||void 0===e?void 0:e.senderPublicKey,receiverPublicKey:null===e||void 0===e?void 0:e.receiverPublicKey}}function ml(e){return e.type===ol&&"string"==typeof e.senderPublicKey&&"string"==typeof e.receiverPublicKey}var wl=Object.defineProperty,vl=Object.getOwnPropertySymbols,bl=Object.prototype.hasOwnProperty,_l=Object.prototype.propertyIsEnumerable,El=(e,t,i)=>t in e?wl(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,Sl=(e,t)=>{for(var i in t||(t={}))bl.call(t,i)&&El(e,i,t[i]);if(vl)for(var i of vl(t))_l.call(t,i)&&El(e,i,t[i]);return e};const Il="ReactNative",Ol={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},Nl="js";function Pl(){return typeof a<"u"&&typeof a.versions<"u"&&typeof a.versions.node<"u"}function Rl(){return!Ts()&&!!xs()&&navigator.product===Il}function Tl(){return!Pl()&&!!xs()}function xl(){var e;const t=Rl()?Ol.reactNative:Pl()?Ol.node:Tl()?Ol.browser:Ol.unknown;return t===Ol.browser?[t,(null==(e=As())?void 0:e.host)||"unknown"].join(":"):t}function Al(e,t,i){const s=function(){const e=Is();if(null===e)return"unknown";const t=e.os?e.os.replace(" ","").toLowerCase():"unknown";return"browser"===e.type?[t,e.name,e.version].join("-"):[t,e.version].join("-")}(),r=xl();return[[e,t].join("-"),[Nl,i].join("-"),s,r].join("/")}function Cl(e){let{protocol:t,version:i,relayUrl:s,sdkVersion:r,auth:n,projectId:o,useOnCloseEvent:a}=e;const c=s.split("?"),h={auth:n,ua:Al(t,i,r),projectId:o,useOnCloseEvent:a||void 0},l=function(e,t){let i=Ms.parse(e);return i=Sl(Sl({},i),t),Ms.stringify(i)}(c[1]||"",h);return c[0]+"?"+l}function Ll(e,t){return e.filter((e=>t.includes(e))).length===e.length}function Ul(e){return Object.fromEntries(e.entries())}function Ml(e){return new Map(Object.entries(e))}function Dl(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:W.FIVE_MINUTES,t=arguments.length>1?arguments[1]:void 0;const i=W.toMiliseconds(e||W.FIVE_MINUTES);let s,r,n;return{resolve:e=>{n&&s&&(clearTimeout(n),s(e))},reject:e=>{n&&r&&(clearTimeout(n),r(e))},done:()=>new Promise(((e,o)=>{n=setTimeout((()=>{o(new Error(t))}),i),s=e,r=o}))}}function jl(e,t,i){return new Promise((async(s,r)=>{const n=setTimeout((()=>r(new Error(i))),t);try{s(await e)}catch(o){r(o)}clearTimeout(n)}))}function kl(e,t){if("string"==typeof t&&t.startsWith(`${e}:`))return t;if("topic"===e.toLowerCase()){if("string"!=typeof t)throw new Error('Value must be "string" for expirer target type: topic');return`topic:${t}`}if("id"===e.toLowerCase()){if("number"!=typeof t)throw new Error('Value must be "number" for expirer target type: id');return`id:${t}`}throw new Error(`Unknown expirer target type: ${e}`)}function zl(e){const[t,i]=e.split(":"),s={id:void 0,topic:void 0};if("topic"===t&&"string"==typeof i)s.topic=i;else{if("id"!==t||!Number.isInteger(Number(i)))throw new Error(`Invalid target, expected id:number or topic:string, got ${t}:${i}`);s.id=Number(i)}return s}function ql(e,t){return W.fromMiliseconds((t||Date.now())+W.toMiliseconds(e))}function $l(e){return Date.now()>=W.toMiliseconds(e)}function Kl(e,t){return`${e}${t?`:${t}`:""}`}function Vl(e){return(null===e||void 0===e?void 0:e.relay)||{protocol:"irn"}}function Hl(e){const t=Fs[e];if(typeof t>"u")throw new Error(`Relay Protocol not supported: ${e}`);return t}var Fl=Object.defineProperty,Bl=Object.getOwnPropertySymbols,Gl=Object.prototype.hasOwnProperty,Wl=Object.prototype.propertyIsEnumerable,Yl=(e,t,i)=>t in e?Fl(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i;function Jl(e){const t={},i="relay"+(arguments.length>1&&void 0!==arguments[1]?arguments[1]:"-");return Object.keys(e).forEach((s=>{if(s.startsWith(i)){const r=s.replace(i,""),n=e[s];t[r]=n}})),t}function Ql(e){return e.startsWith("//")?e.substring(2):e}function Xl(e){return`${e.protocol}
2:${e.topic}@${e.version}?`+Ms.stringify(((e,t)=>{for(var i in t||(t={}))Gl.call(t,i)&&Yl(e,i,t[i]);if(Bl)for(var i of Bl(t))Wl.call(t,i)&&Yl(e,i,t[i]);return e})({symKey:e.symKey},function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"-";const i={};return Object.keys(e).forEach((s=>{const r="relay"+t+s;e[s]&&(i[r]=e[s])})),i}(e.relay)))}function Zl(e){const t=[];return e.forEach((e=>{const[i,s]=e.split(":");t.push(`${i}:${s}`)})),t}const eu={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}},tu={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 iu(e,t){const{message:i,code:s}=tu[e];return{message:t?`${i} ${t}`:i,code:s}}function su(e,t){const{message:i,code:s}=eu[e];return{message:t?`${i} ${t}`:i,code:s}}function ru(e,t){return!!Array.isArray(e)&&(!(typeof t<"u"&&e.length)||e.every(t))}function nu(e){return Object.getPrototypeOf(e)===Object.prototype&&Object.keys(e).length}function ou(e){return typeof e>"u"}function au(e,t){return!(!t||!ou(e))||"string"==typeof e&&!!e.trim().length}function cu(e,t){return!(!t||!ou(e))||"number"==typeof e&&!isNaN(e)}function hu(e){return!(!au(e,!1)||!e.includes(":"))&&2===e.split(":").length}function lu(e){let t=!0;return ru(e)?e.length&&(t=e.every((e=>au(e,!1)))):t=!1,t}function uu(e,t){let i=null;return Object.entries(e).forEach((e=>{let[s,r]=e;if(i)return;const n=function(e,t,i){let s=null;return ru(t)?t.forEach((t=>{s||(!hu(t)||!t.includes(e))&&(s=su("UNSUPPORTED_CHAINS",`${i}, chain ${t} should be a string and conform to "namespace:chainId" format`))})):s=su("UNSUPPORTED_CHAINS",`${i}, chains ${t} should be an array of strings conforming to "namespace:chainId" format`),s}(s,el(s,r),`${t} requiredNamespace`);n&&(i=n)})),i}function du(e,t){let i=null;return ru(e)?e.forEach((e=>{i||function(e){if(au(e,!1)&&e.includes(":")){const t=e.split(":");if(3===t.length){const e=t[0]+":"+t[1];return!!t[2]&&hu(e)}}return!1}(e)||(i=su("UNSUPPORTED_ACCOUNTS",`${t}, account ${e} should be a string and conform to "namespace:chainId:address" format`))})):i=su("UNSUPPORTED_ACCOUNTS",`${t}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),i}function pu(e,t){let i=null;return Object.values(e).forEach((e=>{if(i)return;const s=function(e,t){let i=null;return lu(null===e||void 0===e?void 0:e.methods)?lu(null===e||void 0===e?void 0:e.events)||(i=su("UNSUPPORTED_EVENTS",`${t}
2, events should be an array of strings or empty array for no events`)):i=su("UNSUPPORTED_METHODS",`${t}, methods should be an array of strings or empty array for no methods`),i}(e,`${t}, namespace`);s&&(i=s)})),i}function gu(e,t){let i=null;if(e&&nu(e)){const s=pu(e,t);s&&(i=s);const r=function(e,t){let i=null;return Object.values(e).forEach((e=>{if(i)return;const s=du(null===e||void 0===e?void 0:e.accounts,`${t} namespace`);s&&(i=s)})),i}(e,t);r&&(i=r)}else i=iu("MISSING_OR_INVALID",`${t}, namespaces should be an object with data`);return i}function fu(e){return au(e.protocol,!0)}function yu(e){return typeof e<"u"&&null!==typeof e}function mu(e,t){return!(!hu(t)||!function(e){const t=[];return Object.values(e).forEach((e=>{t.push(...Zl(e.accounts))})),t}(e).includes(t))}function wu(e,t,i){return!!au(i,!1)&&function(e,t){const i=[];return Object.values(e).forEach((e=>{Zl(e.accounts).includes(t)&&i.push(...e.methods)})),i}(e,t).includes(i)}function vu(e,t,i){return!!au(i,!1)&&function(e,t){const i=[];return Object.values(e).forEach((e=>{Zl(e.accounts).includes(t)&&i.push(...e.events)})),i}(e,t).includes(i)}function bu(e,t,i){let s=null;const r=function(e){const t={};return Object.keys(e).forEach((i=>{var s;i.includes(":")?t[i]=e[i]:null==(s=e[i].chains)||s.forEach((s=>{t[s]={methods:e[i].methods,events:e[i].events}}))})),t}(e),n=function(e){const t={};return Object.keys(e).forEach((i=>{var s;i.includes(":")?t[i]=e[i]:null===(s=Zl(e[i].accounts))||void 0===s||s.forEach((s=>{t[s]={accounts:e[i].accounts.filter((e=>e.includes(`${s}:`))),methods:e[i].methods,events:e[i].events}}))})),t}(t),o=Object.keys(r),a=Object.keys(n),c=_u(Object.keys(e)),h=_u(Object.keys(t)),l=c.filter((e=>!h.includes(e)));return l.length&&(s=iu("NON_CONFORMING_NAMESPACES",`${i} namespaces keys don't satisfy requiredNamespaces.\n      Required: ${l.toString()}\n      Received: ${Object.keys(t).toString()}`)),Ll(o,a)||(s=iu("NON_CONFORMING_NAMESPACES",`${i} namespaces chains don't satisfy required namespaces.\n      Required: ${o.toString()}\n      Approved: ${a.toString()}`)),Object.keys(t).forEach((e=>{if(!e.includes(":")||s)return;const r=Zl(t[e].accounts);r.includes(e)||(s=iu("NON_CONFORMING_NAMESPACES",`${i} namespaces accounts don't satisfy namespace accounts for ${e}\n        Required: ${e}\n        Approved: ${r.toString()}`))})),o.forEach((e=>{s||(Ll(r[e].methods,n[e].methods)?Ll(r[e].events,n[e].events)||(s=iu("NON_CONFORMING_NAMESPACES",`${i} namespaces events don't satisfy namespace events for ${e}`)):s=iu("NON_CONFORMING_NAMESPACES",`${i} namespaces methods don't satisfy namespace methods for ${e}`))})),s}function _u(e){return[...new Set(e.map((e=>e.includes(":")?e.split(":")[0]:e)))]}var Eu=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var i=new Uint8Array(256),s=0;s<i.length;s++)i[s]=255;for(var r=0;r<e.length;r++){var n=e.charAt(r),o=n.charCodeAt(0);if(255!==i[o])throw new TypeError(n+" is ambiguous");i[o]=r}var a=e.length,c=e.charAt(0),h=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function u(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;var t=0;if(" "!==e[t]){for(var s=0,r=0;e[t]===c;)s++,t++;for(var n=(e.length-t)*h+1>>>0,o=new Uint8Array(n);e[t];){var l=i[e.charCodeAt(t)];if(255===l)return;for(var u=0,d=n-1;(0!==l||u<r)&&-1!==d;d--,u++)l+=a*o[d]>>>0,o[d]=l%256>>>0,l=l/256>>>0;if(0!==l)throw new Error("Non-zero carry");r=u,t++}if(" "!==e[t]){for(var p=n-r;p!==n&&0===o[p];)p++;for(var g=new Uint8Array(s+(n-p)),f=s;p!==n;)g[f++]=o[p++];return g}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var i=0,s=0,r=0,n=t.length;r!==n&&0===t[r];)r++,i++;for(var o=(n-r)*l+1>>>0,h=new Uint8Array(o);r!==n;){for(var u=t[r],d=0,p=o-1;(0!==u||d<s)&&-1!==p;p--,d++)u+=256*h[p]>>>0,h[p]=u%a>>>0,u=u/a>>>0;if(0!==u)throw new Error("Non-zero carry");s=d,r++}for(var g=o-s;g!==o&&0===h[g];)g++;for(var f=c.repeat(i);g<o;++g)f+=e.charAt(h[g]);return f},decodeUnsafe:u,decode:function(e){var i=u(e);if(i)return i;throw new Error(`Non-${t} character`)}}},Su=Eu;const Iu=e=>{if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")};class Ou{constructor(e,t,i){this.name=e,this.prefix=t,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class Nu{constructor(e,t,i){if(this.name=e,this.prefix=t,void 0===t.codePointAt(0))throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=i}decode(e){if("string"==typeof e){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name}
2 decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}throw Error("Can only multibase decode strings")}or(e){return Ru(this,e)}}class Pu{constructor(e){this.decoders=e}or(e){return Ru(this,e)}decode(e){const t=e[0],i=this.decoders[t];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Ru=(e,t)=>new Pu({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}});class Tu{constructor(e,t,i,s){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=s,this.encoder=new Ou(e,t,i),this.decoder=new Nu(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const xu=e=>{let{name:t,prefix:i,encode:s,decode:r}=e;return new Tu(t,i,s,r)},Au=e=>{let{prefix:t,name:i,alphabet:s}=e;const{encode:r,decode:n}=Su(s,i);return xu({prefix:t,name:i,encode:r,decode:e=>Iu(n(e))})},Cu=e=>{let{name:t,prefix:i,bitsPerChar:s,alphabet:r}=e;return xu({prefix:i,name:t,encode:e=>((e,t,i)=>{const s="="===t[t.length-1],r=(1<<i)-1;let n="",o=0,a=0;for(let c=0;c<e.length;++c)for(a=a<<8|e[c],o+=8;o>i;)o-=i,n+=t[r&a>>o];if(o&&(n+=t[r&a<<i-o]),s)for(;n.length*i&7;)n+="=";return n})(e,r,s),decode:e=>((e,t,i,s)=>{const r={};for(let l=0;l<t.length;++l)r[t[l]]=l;let n=e.length;for(;"="===e[n-1];)--n;const o=new Uint8Array(n*i/8|0);let a=0,c=0,h=0;for(let l=0;l<n;++l){const t=r[e[l]];if(void 0===t)throw new SyntaxError(`Non-${s} character`);c=c<<i|t,a+=i,a>=8&&(a-=8,o[h++]=255&c>>a)}if(a>=i||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o})(e,r,s,t)})},Lu=xu({prefix:"\0",name:"identity",encode:e=>(e=>(new TextDecoder).decode(e))(e),decode:e=>(e=>(new TextEncoder).encode(e))(e)});var Uu=Object.freeze({__proto__:null,identity:Lu});const Mu=Cu({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Du=Object.freeze({__proto__:null,base2:Mu});const ju=Cu({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ku=Object.freeze({__proto__:null,base8:ju});const zu=Au({prefix:"9",name:"base10",alphabet:"0123456789"});var qu=Object.freeze({__proto__:null,base10:zu});const $u=Cu({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Ku=Cu({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Vu=Object.freeze({__proto__:null,base16:$u,base16upper:Ku});const Hu=Cu({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Fu=Cu({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Bu=Cu({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Gu=Cu({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Wu=Cu({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Yu=Cu({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Ju=Cu({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Qu=Cu({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Xu=Cu({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Zu=Object.freeze({__proto__:null,base32:Hu,base32upper:Fu,base32pad:Bu,base32padupper:Gu,base32hex:Wu,base32hexupper:Yu,base32hexpad:Ju,base32hexpadupper:Qu,base32z:Xu});const ed=Au({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),td=Au({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var id=Object.freeze({__proto__:null,base36:ed,base36upper:td});const sd=Au({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),rd=Au({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var nd=Object.freeze({__proto__:null,base58btc:sd,base58flickr:rd});const od=Cu({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
2+/",bitsPerChar:6}),ad=Cu({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),cd=Cu({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),hd=Cu({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ld=Object.freeze({__proto__:null,base64:od,base64pad:ad,base64url:cd,base64urlpad:hd});const ud=Array.from("\ud83d\ude80\ud83e\ude90\u2604\ud83d\udef0\ud83c\udf0c\ud83c\udf11\ud83c\udf12\ud83c\udf13\ud83c\udf14\ud83c\udf15\ud83c\udf16\ud83c\udf17\ud83c\udf18\ud83c\udf0d\ud83c\udf0f\ud83c\udf0e\ud83d\udc09\u2600\ud83d\udcbb\ud83d\udda5\ud83d\udcbe\ud83d\udcbf\ud83d\ude02\u2764\ud83d\ude0d\ud83e\udd23\ud83d\ude0a\ud83d\ude4f\ud83d\udc95\ud83d\ude2d\ud83d\ude18\ud83d\udc4d\ud83d\ude05\ud83d\udc4f\ud83d\ude01\ud83d\udd25\ud83e\udd70\ud83d\udc94\ud83d\udc96\ud83d\udc99\ud83d\ude22\ud83e\udd14\ud83d\ude06\ud83d\ude44\ud83d\udcaa\ud83d\ude09\u263a\ud83d\udc4c\ud83e\udd17\ud83d\udc9c\ud83d\ude14\ud83d\ude0e\ud83d\ude07\ud83c\udf39\ud83e\udd26\ud83c\udf89\ud83d\udc9e\u270c\u2728\ud83e\udd37\ud83d\ude31\ud83d\ude0c\ud83c\udf38\ud83d\ude4c\ud83d\ude0b\ud83d\udc97\ud83d\udc9a\ud83d\ude0f\ud83d\udc9b\ud83d\ude42\ud83d\udc93\ud83e\udd29\ud83d\ude04\ud83d\ude00\ud83d\udda4\ud83d\ude03\ud83d\udcaf\ud83d\ude48\ud83d\udc47\ud83c\udfb6\ud83d\ude12\ud83e\udd2d\u2763\ud83d\ude1c\ud83d\udc8b\ud83d\udc40\ud83d\ude2a\ud83d\ude11\ud83d\udca5\ud83d\ude4b\ud83d\ude1e\ud83d\ude29\ud83d\ude21\ud83e\udd2a\ud83d\udc4a\ud83e\udd73\ud83d\ude25\ud83e\udd24\ud83d\udc49\ud83d\udc83\ud83d\ude33\u270b\ud83d\ude1a\ud83d\ude1d\ud83d\ude34\ud83c\udf1f\ud83d\ude2c\ud83d\ude43\ud83c\udf40\ud83c\udf37\ud83d\ude3b\ud83d\ude13\u2b50\u2705\ud83e\udd7a\ud83c\udf08\ud83d\ude08\ud83e\udd18\ud83d\udca6\u2714\ud83d\ude23\ud83c\udfc3\ud83d\udc90\u2639\ud83c\udf8a\ud83d\udc98\ud83d\ude20\u261d\ud83d\ude15\ud83c\udf3a\ud83c\udf82\ud83c\udf3b\ud83d\ude10\ud83d\udd95\ud83d\udc9d\ud83d\ude4a\ud83d\ude39\ud83d\udde3\ud83d\udcab\ud83d\udc80\ud83d\udc51\ud83c\udfb5\ud83e\udd1e\ud83d\ude1b\ud83d\udd34\ud83d\ude24\ud83c\udf3c\ud83d\ude2b\u26bd\ud83e\udd19\u2615\ud83c\udfc6\ud83e\udd2b\ud83d\udc48\ud83d\ude2e\ud83d\ude46\ud83c\udf7b\ud83c\udf43\ud83d\udc36\ud83d\udc81\ud83d\ude32\ud83c\udf3f\ud83e\udde1\ud83c\udf81\u26a1\ud83c\udf1e\ud83c\udf88\u274c\u270a\ud83d\udc4b\ud83d\ude30\ud83e\udd28\ud83d\ude36\ud83e\udd1d\ud83d\udeb6\ud83d\udcb0\ud83c\udf53\ud83d\udca2\ud83e\udd1f\ud83d\ude41\ud83d\udea8\ud83d\udca8\ud83e\udd2c\u2708\ud83c\udf80\ud83c\udf7a\ud83e\udd13\ud83d\ude19\ud83d\udc9f\ud83c\udf31\ud83d\ude16\ud83d\udc76\ud83e\udd74\u25b6\u27a1\u2753\ud83d\udc8e\ud83d\udcb8\u2b07\ud83d\ude28\ud83c\udf1a\ud83e\udd8b\ud83d\ude37\ud83d\udd7a\u26a0\ud83d\ude45\ud83d\ude1f\ud83d\ude35\ud83d\udc4e\ud83e\udd32\ud83e\udd20\ud83e\udd27\ud83d\udccc\ud83d\udd35\ud83d\udc85\ud83e\uddd0\ud83d\udc3e\ud83c\udf52\ud83d\ude17\ud83e\udd11\ud83c\udf0a\ud83e\udd2f\ud83d\udc37\u260e\ud83d\udca7\ud83d\ude2f\ud83d\udc86\ud83d\udc46\ud83c\udfa4\ud83d\ude47\ud83c\udf51\u2744\ud83c\udf34\ud83d\udca3\ud83d\udc38\ud83d\udc8c\ud83d\udccd\ud83e\udd40\ud83e\udd22\ud83d\udc45\ud83d\udca1\ud83d\udca9\ud83d\udc50\ud83d\udcf8\ud83d\udc7b\ud83e\udd10\ud83e\udd2e\ud83c\udfbc\ud83e\udd75\ud83d\udea9\ud83c\udf4e\ud83c\udf4a\ud83d\udc7c\ud83d\udc8d\ud83d\udce3\ud83e\udd42"),dd=ud.reduce(((e,t,i)=>(e[i]=t,e)),[]),pd=ud.reduce(((e,t,i)=>(e[t.codePointAt(0)]=i,e)),[]);const gd=xu({prefix:"\ud83d\ude80",name:"base256emoji",encode:function(e){return e.reduce(((e,t)=>e+=dd[t]),"")},decode:function(e){const t=[];for(const i of e){const e=pd[i.codePointAt(0)];if(void 0===e)throw new Error(`Non-base256emoji character: ${i}`);t.push(e)}return new Uint8Array(t)}});var fd=Object.freeze({__proto__:null,base256emoji:gd}),yd=function e(t,i,s){i=i||[];for(var r=s=s||0;t>=vd;)i[s++]=255&t|md,t/=128;for(;t&wd;)i[s++]=255&t|md,t>>>=7;return i[s]=0|t,e.bytes=s-r+1,i},md=128,wd=-128,vd=Math.pow(2,31);var bd=function e(t,i){var s,r=0,n=0,o=i=i||0,a=t.length;do{if(o>=a)throw e.bytes=0,new RangeError("Could not decode varint");s=t[o++],r+=n<28?(s&Ed)<<n:(s&Ed)*Math.pow(2,n),n+=7}while(s>=_d);return e.bytes=o-i,r},_d=128,Ed=127;var Sd=Math.pow(2,7),Id=Math.pow(2,14),Od=Math.pow(2,21),Nd=Math.pow(2,28),Pd=Math.pow(2,35),Rd=Math.pow(2,42),Td=Math.pow(2,49),xd=Math.pow(2,56),Ad=Math.pow(2,63),Cd={encode:yd,decode:bd,encodingLength:function(e){return e<Sd?1:e<Id?2:e<Od?3:e<Nd?4:e<Pd?5:e<Rd?6:e<Td?7:e<xd?8:e<Ad?9:10}},Ld=Cd;const Ud=function(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;return Ld.encode(e,t,i),t},Md=e=>Ld.encodingLength(e),Dd=(e,t)=>{const i=t.byteLength,s=Md(e),r=s+Md(i),n=new Uint8Array(r+i);return Ud(e,n,0),Ud(i,n,s),n.set(t,r),new jd(e,i,t,n)};
2class jd{constructor(e,t,i,s){this.code=e,this.size=t,this.digest=i,this.bytes=s}}const kd=e=>{let{name:t,code:i,encode:s}=e;return new zd(t,i,s)};class zd{constructor(e,t,i){this.name=e,this.code=t,this.encode=i}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?Dd(this.code,t):t.then((e=>Dd(this.code,e)))}throw Error("Unknown type, must be binary type")}}const qd=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),$d=kd({name:"sha2-256",code:18,encode:qd("SHA-256")}),Kd=kd({name:"sha2-512",code:19,encode:qd("SHA-512")});Object.freeze({__proto__:null,sha256:$d,sha512:Kd});const Vd=Iu,Hd={code:0,name:"identity",encode:Vd,digest:e=>Dd(0,Vd(e))};Object.freeze({__proto__:null,identity:Hd});new TextEncoder,new TextDecoder;const Fd={...Uu,...Du,...ku,...qu,...Vu,...Zu,...id,...nd,...ld,...fd};function Bd(e){return null!=globalThis.Buffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function Gd(e,t,i,s){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:i},decoder:{decode:s}}}const Wd=Gd("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),Yd=Gd("ascii","a",(e=>{let t="a";for(let i=0;i<e.length;i++)t+=String.fromCharCode(e[i]);return t}),(e=>{const t=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return null!=globalThis.Buffer&&null!=globalThis.Buffer.allocUnsafe?Bd(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}((e=e.substring(1)).length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t})),Jd={utf8:Wd,"utf-8":Wd,hex:Fd.base16,latin1:Yd,ascii:Yd,binary:Yd,...Fd};const Qd="core",Xd=`wc@2:${Qd}:`,Zd="error",ep={database:":memory:"},tp="client_ed25519_seed",ip=W.ONE_DAY,sp=W.SIX_HOURS,rp="wss://relay.walletconnect.com",np="relayer_message",op="relayer_message_ack",ap="relayer_connect",cp="relayer_disconnect",hp="relayer_error",lp="relayer_connection_stalled",up="relayer_transport_closed",dp="relayer_publish",pp="payload",gp="connect",fp="disconnect",yp="error",mp=W.ONE_SECOND/2,wp="subscription_created",vp="subscription_deleted",bp="subscription_sync",_p="subscription_resubscribed",Ep=1e3*W.FIVE_SECONDS,Sp={wc_pairingDelete:{req:{ttl:W.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:W.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:W.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:W.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:W.ONE_DAY,prompt:!1,tag:0},res:{ttl:W.ONE_DAY,prompt:!1,tag:0}}},Ip="history_created",Op="history_updated",Np="history_deleted",Pp="history_sync",Rp="expirer_created",Tp="expirer_deleted",xp="expirer_expired",Ap="expirer_sync",Cp="verify-api",Lp="https://verify.walletconnect.com";class Up{constructor(e,t){this.core=e,this.logger=t,this.keychain=new Map,this.name="keychain",this.version="0.3",this.initialized=!1,this.storagePrefix=Xd,this.init=async()=>{if(!this.initialized){const e=await this.getKeyChain();typeof e<"u"&&(this.keychain=e),this.initialized=!0}},this.has=e=>(this.isInitialized(),this.keychain.has(e)),this.set=async(e,t)=>{this.isInitialized(),this.keychain.set(e,t),await this.persist()},this.get=e=>{this.isInitialized();const t=this.keychain.get(e);if(typeof t>"u"){const{message:t}=iu("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t},this.del=async e=>{this.isInitialized(),this.keychain.delete(e),await this.persist()},this.core=e,this.logger=Le.generateChildLogger(t,this.name)}get context(){return Le.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Ul(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Ml(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=iu("NOT_INITIALIZED",this.name);throw new Error(e)}}}class Mp{constructor(e,t,i){this.core=e,this.logger=t,this.name="crypto",this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=e=>(this.isInitialized(),this.keychain.has(e)),this.getClientId=async()=>{this.isInitialized();return qi(Ki(await this.getClientSeed()).publicKey)},this.generateKeyPair=()=>{this.isInitialized();const e=function(){const e=ps.generateKeyPair();return{privateKey:ji(e.secretKey,il),publicKey:ji(e.publicKey,il)}}();return this.setPrivateKey(e.publicKey,e.privateKey)},this.signJWT=async e=>{this.isInitialized();const t=Ki(await this.getClientSeed()),i=ul();return await Vi(i,e,ip,t)},this.generateSharedKey=(e,t,i)=>{this.isInitialized();const s=function(e,t){const i=ps.sharedKey(ki(e,il),ki(t,il));return ji(new us(ds.SHA256,i).expand(ll),il)}(this.getPrivateKey(e),t);return this.setSymKey(s,i)},this.setSymKey=async(e,t)=>{this.isInitialized();const i=t||function(e){return ji(ds.hash(ki(e,il)),il)}(e);return await this.keychain.set(i,e),i},this.deleteKeyPair=async e=>{this.isInitialized(),await this.keychain.del(e)},this.deleteSymKey=async e=>{this.isInitialized(),await this.keychain.del(e)},this.encode=async(e,t,i)=>{this.isInitialized();const s=yl(i),r=Ze(t);if(ml(s)){const t=s.senderPublicKey,i=s.receiverPublicKey;e=await this.generateSharedKey(t,i)}const n=this.getSymKey(e),{type:o,senderPublicKey:a}=s;return gl({type:o,symKey:n,message:r,senderPublicKey:a})},this.decode=async(e,t,i)=>{this.isInitialized();const s=function(e,t){const i=fl(e);return yl({type:pl(i.type),senderPublicKey:typeof i.senderPublicKey<"u"?ji(i.senderPublicKey,il):void 0,receiverPublicKey:null===t||void 0===t?void 0:t.receiverPublicKey})}(t,i);if(ml(s)){const t=s.receiverPublicKey,i=s.senderPublicKey;e=await this.generateSharedKey(t,i)}const r=function(e){const t=new Hi.ChaCha20Poly1305(ki(e.symKey,il)),{sealed:i,iv:s}=fl(e.encoded),r=t.open(s,i);if(null===r)throw new Error("Failed to decrypt");return ji(r,rl)}({symKey:this.getSymKey(e),encoded:t});return Xe(r)},this.getPayloadType=e=>pl(fl(e).type),this.getPayloadSenderPublicKey=e=>{const t=fl(e);return t.senderPublicKey?ji(t.senderPublicKey,il):void 0},this.core=e,this.logger=Le.generateChildLogger(t,this.name),this.keychain=i||new Up(this.core,this.logger)}get context(){return Le.getLoggerContext(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(tp)}catch{e=ul(),await this.keychain.set(tp,e)}return function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"utf8";const i=Jd[t];if(!i)throw new Error(`Unsupported encoding "${t}"`);return"utf8"!==t&&"utf-8"!==t||null==globalThis.Buffer||null==globalThis.Buffer.from?i.decoder.decode(`${i.prefix}${e}`):Bd(globalThis.Buffer.from(e,"utf-8"))}(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=iu("NOT_INITIALIZED",this.name);throw new Error(e)}}}class Dp extends Kh{constructor(e,t){super(e,t),this.logger=e,this.core=t,this.messages=new Map,this.name="messages",this.version="0.3",this.initialized=!1,this.storagePrefix=Xd,this.init=async()=>
2{if(!this.initialized){this.logger.trace("Initialized");try{const e=await this.getRelayerMessages();typeof e<"u"&&(this.messages=e),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}finally{this.initialized=!0}}},this.set=async(e,t)=>{this.isInitialized();const i=dl(t);let s=this.messages.get(e);return typeof s>"u"&&(s={}),typeof s[i]<"u"||(s[i]=t,this.messages.set(e,s),await this.persist()),i},this.get=e=>{this.isInitialized();let t=this.messages.get(e);return typeof t>"u"&&(t={}),t},this.has=(e,t)=>{this.isInitialized();return typeof this.get(e)[dl(t)]<"u"},this.del=async e=>{this.isInitialized(),this.messages.delete(e),await this.persist()},this.logger=Le.generateChildLogger(e,this.name),this.core=t}get context(){return Le.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,Ul(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Ml(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=iu("NOT_INITIALIZED",this.name);throw new Error(e)}}}class jp extends Vh{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.events=new O.EventEmitter,this.name="publisher",this.queue=new Map,this.publishTimeout=1e4,this.publish=async(e,t,i)=>{this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:e,message:t,opts:i}});try{const s=(null===i||void 0===i?void 0:i.ttl)||sp,r=Vl(i),n=(null===i||void 0===i?void 0:i.prompt)||!1,o=(null===i||void 0===i?void 0:i.tag)||0,a=(null===i||void 0===i?void 0:i.id)||Mn().toString(),c={topic:e,message:t,opts:{ttl:s,relay:r,prompt:n,tag:o,id:a}};this.queue.set(a,c);try{await await jl(this.rpcPublish(e,t,s,r,n,o,a),this.publishTimeout),this.relayer.events.emit(dp,c)}catch{return this.logger.debug("Publishing Payload stalled"),void this.relayer.events.emit(lp)}this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:e,message:t,opts:i}})}catch(s){throw this.logger.debug("Failed to Publish Payload"),this.logger.error(s),s}},this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.relayer=e,this.logger=Le.generateChildLogger(t,this.name),this.registerEventListeners()}get context(){return Le.getLoggerContext(this.logger)}rpcPublish(e,t,i,s,r,n,o){var a,c,h,l;const u={method:Hl(s.protocol).publish,params:{topic:e,message:t,ttl:i,prompt:r,tag:n},id:o};return ou(null==(a=u.params)?void 0:a.prompt)&&(null==(c=u.params)||delete c.prompt),ou(null==(h=u.params)?void 0:h.tag)&&(null==(l=u.params)||delete l.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:u}),this.relayer.request(u)}onPublish(e){this.queue.delete(e)}checkQueue(){this.queue.forEach((async e=>{const{topic:t,message:i,opts:s}=e;await this.publish(t,i,s)}))}registerEventListeners(){this.relayer.core.heartbeat.on(B.HEARTBEAT_EVENTS.pulse,(()=>{this.checkQueue()})),this.relayer.on(op,(e=>{this.onPublish(e.id.toString())}))}}class kp{constructor(){this.map=new Map,this.set=(e,t)=>{const i=this.get(e);this.exists(e,t)||this.map.set(e,[...i,t])},this.get=e=>this.map.get(e)||[],this.exists=(e,t)=>this.get(e).includes(t),this.delete=(e,t)=>{if(typeof t>"u")return void this.map.delete(e);if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,t))return;const s=i.filter((e=>e!==t));s.length?this.map.set(e,s):this.map.delete(e)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}}var zp=Object.defineProperty,qp=Object.defineProperties,$p=Object.getOwnPropertyDescriptors,Kp=Object.getOwnPropertySymbols,Vp=Object.prototype.hasOwnProperty,Hp=Object.prototype.propertyIsEnumerable,Fp=(e,t,i)=>t in e?zp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,Bp=(e,t)=>{for(var i in t||(t={}))Vp.call(t,i)&&Fp(e,i,t[i]);if(Kp)for(var i of Kp(t))Hp.call(t,i)&&Fp(e,i,t[i]);return e},Gp=(e,t)=>qp(e,$p(t));class Wp extends Bh{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.subscriptions=new Map,this.topicMap=new kp,this.events=new O.EventEmitter,this.name="subscription",this.version="0.3",this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=Xd,this.subscribeTimeout=1e4,this.restartInProgress=!1,this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restart(),this.registerEventListeners(),this.onEnable(),this.clientId=await this.relayer.core.crypto.getClientId())},this.subscribe=async(e,t)=>{await this.restartToComplete(),this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:e,opts:t}});try{const i=Vl(t),s={topic:e,relay:i};this.pending.set(e,s);const r=await this.rpcSubscribe(e,i);return this.onSubscribe(r,s),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:e,opts:t}}),r}catch(i){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(i),i}},this.unsubscribe=async(e,t)=>{await this.restartToComplete(),this.isInitialized(),typeof(null===t||void 0===t?void 0:t.id)<"u"?await this.unsubscribeById(e,t.id,t):await this.unsubscribeByTopic(e,t)},this.isSubscribed=async e=>!!this.topics.includes(e)||await new Promise(((t,i)=>{const s=new W.Watch;s.start(this.pendingSubscriptionWatchLabel);const r=setInterval((()=>{!this.pending.has(e)&&this.topics.includes(e)&&(clearInterval(r),s.stop(this.pendingSubscriptionWatchLabel),t(!0)),s.elapsed(this.pendingSubscriptionWatchLabel)>
2=Ep&&(clearInterval(r),s.stop(this.pendingSubscriptionWatchLabel),i(new Error("Subscription resolution timeout")))}),this.pollingInterval)})).catch((()=>!1)),this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=Le.generateChildLogger(t,this.name),this.clientId=""}get context(){return Le.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+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}hasSubscription(e,t){let i=!1;try{i=this.getSubscription(e).topic===t}catch{}return i}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const i=this.topicMap.get(e);await Promise.all(i.map((async i=>await this.unsubscribeById(e,i,t))))}async unsubscribeById(e,t,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}});try{const s=Vl(i);await this.rpcUnsubscribe(e,t,s);const r=su("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,r),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}})}catch(s){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(s),s}}async rpcSubscribe(e,t){const i={method:Hl(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{await await jl(this.relayer.request(i),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(lp)}return dl(e+this.clientId)}async rpcBatchSubscribe(e){if(!e.length)return;const t={method:Hl(e[0].relay.protocol).batchSubscribe,params:{topics:e.map((e=>e.topic))}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:t});try{return await await jl(this.relayer.request(t),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Payload stalled"),this.relayer.events.emit(lp)}}rpcUnsubscribe(e,t,i){const s={method:Hl(i.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s}),this.relayer.request(s)}onSubscribe(e,t){this.setSubscription(e,Gp(Bp({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach((e=>{this.setSubscription(e.id,Bp({},e)),this.pending.delete(e.topic)}))}async onUnsubscribe(e,t,i){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,i),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,t){this.subscriptions.has(e)||(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,Bp({},t)),this.topicMap.set(t.topic,e),this.events.emit(wp,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:t}=iu("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(vp,Gp(Bp({},i),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(bp)}async reset(){if(this.cached.length){const e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let t=0;t<e;t++){const e=this.cached.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(e)}}this.events.emit(_p)}
2async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:e}=iu("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(e)}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){if(!e.length)return;const t=await this.rpcBatchSubscribe(e);ru(t)&&this.onBatchSubscribe(t.map(((t,i)=>Gp(Bp({},e[i]),{id:t}))))}async onConnect(){this.restartInProgress||(await this.restart(),this.onEnable())}onDisconnect(){this.onDisable()}async checkPending(){if(this.relayer.transportExplicitlyClosed)return;const e=[];this.pending.forEach((t=>{e.push(t)})),await this.batchSubscribe(e)}registerEventListeners(){this.relayer.core.heartbeat.on(B.HEARTBEAT_EVENTS.pulse,(async()=>{await this.checkPending()})),this.relayer.on(ap,(async()=>{await this.onConnect()})),this.relayer.on(cp,(()=>{this.onDisconnect()})),this.events.on(wp,(async e=>{const t=wp;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()})),this.events.on(vp,(async e=>{const t=vp;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()}))}isInitialized(){if(!this.initialized){const{message:e}=iu("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){this.restartInProgress&&await new Promise((e=>{const t=setInterval((()=>{this.restartInProgress||(clearInterval(t),e())}),this.pollingInterval)}))}}var Yp=Object.defineProperty,Jp=Object.getOwnPropertySymbols,Qp=Object.prototype.hasOwnProperty,Xp=Object.prototype.propertyIsEnumerable,Zp=(e,t,i)=>t in e?Yp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i;class eg extends Hh{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new O.EventEmitter,this.name="relayer",this.transportExplicitlyClosed=!1,this.initialized=!1,this.reconnecting=!1,this.connectionStatusPollingInterval=20,this.staleConnectionErrors=["socket hang up","socket stalled"],this.request=async e=>{this.logger.debug("Publishing Request Payload");try{return await this.toEstablishConnection(),await this.provider.request(e)}catch(t){throw this.logger.debug("Failed to Publish Request"),this.logger.error(t),t}},this.core=e.core,this.logger=typeof e.logger<"u"&&"string"!=typeof e.logger?Le.generateChildLogger(e.logger,this.name):Le.pino(Le.getDefaultLoggerOptions({level:e.logger||"error"})),this.messages=new Dp(this.logger,e.core),this.subscriber=new Wp(this,this.logger),this.publisher=new jp(this,this.logger),this.relayUrl=(null===e||void 0===e?void 0:e.relayUrl)||rp,this.projectId=e.projectId,this.provider={}}
2async init(){this.logger.trace("Initialized"),await this.createProvider(),await Promise.all([this.messages.init(),this.transportOpen(),this.subscriber.init()]),this.registerEventListeners(),this.initialized=!0,setTimeout((async()=>{0===this.subscriber.topics.length&&(this.logger.info("No topics subscribted to after init, closing transport"),await this.transportClose(),this.transportExplicitlyClosed=!1)}),1e4)}get context(){return Le.getLoggerContext(this.logger)}get connected(){return this.provider.connection.connected}get connecting(){return this.provider.connection.connecting}async publish(e,t,i){this.isInitialized(),await this.publisher.publish(e,t,i),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now()})}async subscribe(e,t){this.isInitialized();let i="";return await Promise.all([new Promise((t=>{this.subscriber.once(wp,(i=>{i.topic===e&&t()}))})),new Promise((async s=>{i=await this.subscriber.subscribe(e,t),s()}))]),i}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 transportClose(){this.transportExplicitlyClosed=!0,this.connected&&(await this.provider.disconnect(),this.events.emit(up))}async transportOpen(e){if(this.transportExplicitlyClosed=!1,!this.reconnecting){this.relayUrl=e||this.relayUrl,this.reconnecting=!0;try{await Promise.all([new Promise((e=>{this.initialized||e(),this.subscriber.once(_p,(()=>{e()}))})),await Promise.race([new Promise((async(e,t)=>
2{await jl(this.provider.connect(),5e3,"socket stalled").catch((e=>t(e))).then((()=>e())).finally((()=>this.removeListener(up,this.rejectTransportOpen)))})),new Promise((e=>this.once(up,this.rejectTransportOpen)))])])}catch(t){this.logger.error(t);const e=t;if(!this.isConnectionStalled(e.message))throw t;this.events.emit(up)}finally{this.reconnecting=!1}}}async restartTransport(e){this.transportExplicitlyClosed||(this.relayUrl=e||this.relayUrl,this.connected&&await Promise.all([new Promise((e=>{this.provider.once(fp,(()=>{e()}))})),this.transportClose()]),await this.createProvider(),await this.transportOpen())}isConnectionStalled(e){return this.staleConnectionErrors.some((t=>e.includes(t)))}rejectTransportOpen(){throw new Error("closeTransport called before connection was established")}async createProvider(){const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Xn(new to(Cl({sdkVersion:"y",protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0}))),this.registerProviderListeners()}async recordMessageEvent(e){const{topic:t,message:i}=e;await this.messages.set(t,i)}async shouldIgnoreMessageEvent(e){const{topic:t,message:i}=e;return!await this.subscriber.isSubscribed(t)||this.messages.has(t,i)}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Wn(e)){if(!e.method.endsWith("_subscription"))return;const t=e.params,{topic:i,message:s,publishedAt:r}=t.data,n={topic:i,message:s,publishedAt:r};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(((e,t)=>{for(var i in t||(t={}))Qp.call(t,i)&&Zp(e,i,t[i]);if(Jp)for(var i of Jp(t))Xp.call(t,i)&&Zp(e,i,t[i]);return e})({type:"event",event:t.id},n)),this.events.emit(t.id,n),await this.acknowledgePayload(e),await this.onMessageEvent(n)}else Yn(e)&&this.events.emit(op,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(np,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const t=jn(e.id,!0);await this.provider.connection.send(t)}registerProviderListeners(){this.provider.on(pp,(e=>this.onProviderPayload(e))),this.provider.on(gp,(()=>{this.events.emit(ap)})),this.provider.on(fp,(()=>{this.onProviderDisconnect()})),this.provider.on(yp,(e=>{this.logger.error(e),this.events.emit(hp,e)}))}registerEventListeners(){this.events.on(lp,(async()=>{await this.restartTransport()}))}onProviderDisconnect(){this.events.emit(cp),this.attemptToReconnect()}attemptToReconnect(){this.transportExplicitlyClosed||setTimeout((async()=>{await this.restartTransport()}),W.toMiliseconds(mp))}isInitialized(){if(!this.initialized){const{message:e}=iu("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(!this.connected){if(this.connecting)return await new Promise((e=>{const t=setInterval((()=>{this.connected&&(clearInterval(t),e())}),this.connectionStatusPollingInterval)}));await this.restartTransport()}}}var tg=Object.defineProperty,ig=Object.getOwnPropertySymbols,sg=Object.prototype.hasOwnProperty,rg=Object.prototype.propertyIsEnumerable,ng=(e,t,i)=>t in e?tg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,og=(e,t)=>{for(var i in t||(t={}))sg.call(t,i)&&ng(e,i,t[i]);if(ig)for(var i of ig(t))rg.call(t,i)&&ng(e,i,t[i]);return e};class ag extends Fh{constructor(e,t,i){let s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:Xd,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:void 0;super(e,t,i,s),this.core=e,this.logger=t,this.name=i,this.map=new Map,this.version="0.3",this.cached=[],this.initialized=!1,this.storagePrefix=Xd,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach((e=>{this.getKey&&null!==e&&!ou(e)?this.map.set(this.getKey(e),e):function(e){var t;return null==(t=null===e||void 0===e?void 0:e.proposer)?void 0:t.publicKey}(e)?this.map.set(e.id,e):function(e){return null===e||void 0===e?void 0:e.topic}(e)&&this.map.set(e.topic,e)})),this.cached=[],this.initialized=!0)},this.set=async(e,t)=>{this.isInitialized(),this.map.has(e)?await this.update(e,t):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:e,value:t}),this.map.set(e,t),await this.persist())},this.get=e=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:e}),this.getData(e)),this.getAll=e=>(this.isInitialized(),e?this.values.filter((t=>Object.keys(e).every((i=>ro(t[i],e[i]))))):this.values),this.update=async(e,t)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:e,update:t});const i=og(og({},this.getData(e)),t);this.map.set(e,i),await this.persist()},this.delete=async(e,t)=>{this.isInitialized(),this.map.has(e)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",ke
2y:e,reason:t}),this.map.delete(e),await this.persist())},this.logger=Le.generateChildLogger(t,this.name),this.storagePrefix=s,this.getKey=r}get context(){return Le.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}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){const{message:t}=iu("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(t),new Error(t)}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:e}=iu("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}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}=iu("NOT_INITIALIZED",this.name);throw new Error(e)}}}class cg{constructor(e,t){this.core=e,this.logger=t,this.name="pairing",this.version="0.3",this.events=new N,this.initialized=!1,this.storagePrefix=Xd,this.ignoredPayloadTypes=[ol],this.registeredMethods=[],this.init=async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))},this.register=e=>{let{methods:t}=e;this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...t])]},this.create=async()=>{this.isInitialized();const e=ul(),t=await this.core.crypto.setSymKey(e),i=ql(W.FIVE_MINUTES),s={protocol:"irn"},r={topic:t,expiry:i,relay:s,active:!1},n=Xl({protocol:this.core.protocol,version:this.core.version,topic:t,symKey:e,relay:s});return await this.pairings.set(t,r),await this.core.relayer.subscribe(t),this.core.expirer.set(t,i),{topic:t,uri:n}},this.pair=async e=>{this.isInitialized(),this.isValidPair(e);const{topic:t,symKey:i,relay:s}=function(e){const t=e.indexOf(":"),i=-1!==e.indexOf("?")?e.indexOf("?"):void 0,s=e.substring(0,t),r=e.substring(t+1,i).split("@"),n=typeof i<"u"?e.substring(i):"",o=Ms.parse(n);return{protocol:s,topic:Ql(r[0]),version:parseInt(r[1],10),symKey:o.symKey,relay:Jl(o)}}(e.uri);if(this.pairings.keys.includes(t))throw new Error(`Pairing already exists: ${t}`);if(this.core.crypto.hasKeys(t))throw new Error(`Keychain already exists: ${t}`);const r=ql(W.FIVE_MINUTES),n={topic:t,relay:s,expiry:r,active:!1};return await this.pairings.set(t,n),await this.core.crypto.setSymKey(i,t),await this.core.relayer.subscribe(t,{relay:s}),this.core.expirer.set(t,r),e.activatePairing&&await this.activate({topic:t}),n},this.activate=async e=>{let{topic:t}=e;this.isInitialized();const i=ql(W.THIRTY_DAYS);await this.pairings.update(t,{active:!0,expiry:i}),this.core.expirer.set(t,i)},this.ping=async e=>{this.isInitialized(),await this.isValidPing(e);const{topic:t}=e;if(this.pairings.keys.includes(t)){const e=await this.sendRequest(t,"wc_pairingPing",{}),{done:i,resolve:s,reject:r}=Dl();this.events.once(Kl("pairing_ping",e),(e=>{let{error:t}=e;t?r(t):s()})),await i()}},this.updateExpiry=async e=>{let{topic:t,expiry:i}=e;this.isInitialized(),await this.pairings.update(t,{expiry:i})},this.updateMetadata=async e=>{let{topic:t,metadata:i}=e;this.isInitialized(),await this.pairings.update(t,{peerMetadata:i})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async e=>{this.isInitialized(),await this.isValidDisconnect(e);const{topic:t}=e;this.pairings.keys.includes(t)&&(await this.sendRequest(t,"wc_pairingDelete",su("USER_DISCONNECTED")),await this.deletePairing(t))},this.sendRequest=async(e,t,i)=>{const s=Dn(t,i),r=await this.core.crypto.encode(e,s),n=Sp[t].req;return this.core.history.set(e,s),this.core.relayer.publish(e,r,n),s.id},this.sendResult=async(e,t,i)=>{const s=jn(e,i),r=await this.core.crypto.encode(t,s),n=await this.core.history.get(t,e),o=Sp[n.request.method].res;await this.core.relayer.publish(t,r,o),await this.core.history.resolve(s)},this.sendError=async(e,t,i)=>{const s=kn(e,i),r=await this.core.crypto.encode(t,s),n=await this.core.history.get(t,e),o=Sp[n.request.method]?Sp[n.request.method].res:Sp.unregistered_method.res;await this.core.relayer.publish(t,r,o),await this.core.history.resolve(s)},this.deletePairing=async(e,t)=>{await this.core.relayer.unsubscribe(e),await Promise.all([this.pairings.delete(e,su("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(e),t?Promise.resolve():this.core.expirer.del(e)])},this.cleanup=async()=>{const e=this.pairings.getAll().filter((e=>$l(e.expiry)));await Promise.all(e.map((e=>this.deletePairing(e.topic))))},this.onRelayEventRequest=e=>{const{topic:t,payload:i}=e,s=i.method;if(this.pairings.keys.includes(t))switch(s){case"wc_pairingPing":return this.onPairingPingRequest(t,i);case"wc_pairingDelete":return this.onPairingDeleteRequest(t,i);default:return this.onUnknownRpcMethodRequest(t,i)}},this.onRelayEventResponse=async e=>{const{topic:t,payload:i}=e,s=(await this.core.history.get(t,i.id)).request.method;if(this.pairings.keys.includes(t)){if("wc_pairingPing"===s)return this.onPairingPingResponse(t,i);return this.onUnknownRpcMethodResponse(s)}},this.onPairingPingRequest=async(e,t)=>{const{id:i}=t;try{this.isValidPing({topic:e}),await this.sendResult(i,e,!0),this.events.emit("pairing_ping",{id:i,topic:e})}catch(s){await this.sendError(i,e,s),this.logger.error(s)}},this.onPairingPingResponse=(e,t)=>{const{id:i}=t;setTimeout((()=>{Jn(t)?this.events.emit(Kl("pairing_ping",i),{}):Qn(t)&&this.events.emit(Kl("pairing_ping",i),{error:t.error})}),500)},this.onPairingDeleteRequest=async(e,t)=>{const{id:i}=t;try{this.isValidDisconnect({topic:e}),await this.deletePairing(e),this.events.emit("pairing_delete",{id:i,topic:e})}catch(s){await this.sendError(i,e,s),this.logger.error(s)}},this.onUnknownRpcMethodRequest=async(e,t)=>{const{id:i,method:s}=t;try{if(this.registeredMethods.includes(s))return;const t=su("WC_METHOD_UNSUPPORTED",s);await this.sendError(i,e,t),this.logger.error(t)}catch(r){await this.sendError(i,e,r),this.logger.error(r)}},this.onUnknownRpcMethodResponse=e=>{this.registeredMethods.includes(e)||this.logger.error(su("WC_METHOD_UNSUPPORTED",e))},this.isValidPair=e=>{if(!yu(e)){const{message:t}=iu("MISSING_OR_INVALID",`pair() params: ${e}`);throw new Error(t)}if(!function(e){if(au(e,!1))try{return typeof new URL(e)<"u"}catch{return!1}return!1}(e.uri)){const{message:t}=iu("MISSING_OR_INVALID",`pair() uri: ${e.uri}`);throw new Error(t)}},this.isValidPing=async e=>{if(!yu(e)){const{message:t}=iu("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidPairingTopic(t)},this.isValidDisconnect=async e=>{if(!yu(e)){const{message:t}=iu("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidPairingTopic(t)},this.isValidPairingTopic=async e=>{if(!au(e,!1)){const{message:t}=iu("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.pairings.keys.includes(e)){const{message:t}=iu("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if($l(this.pairings.get(e).expiry)){await this.deletePairing(e);const{message:t}=iu("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}},this.core=e,this.logger=Le.generateChildLogger(t,this.name),this.pairings=new ag(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Le.getLoggerContext(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=iu("NOT_INITIALIZED",this.name);throw new Error(e)}}
2registerRelayerEvents(){this.core.relayer.on(np,(async e=>{const{topic:t,message:i}=e;if(this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))return;const s=await this.core.crypto.decode(t,i);Wn(s)?(this.core.history.set(t,s),this.onRelayEventRequest({topic:t,payload:s})):Yn(s)&&(await this.core.history.resolve(s),this.onRelayEventResponse({topic:t,payload:s}))}))}registerExpirerEvents(){this.core.expirer.on(xp,(async e=>{const{topic:t}=zl(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit("pairing_expire",{topic:t}))}))}}class hg extends $h{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.records=new Map,this.events=new O.EventEmitter,this.name="history",this.version="0.3",this.cached=[],this.initialized=!1,this.storagePrefix=Xd,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach((e=>this.records.set(e.id,e))),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(e,t,i)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:e,request:t,chainId:i}),this.records.has(t.id))return;const s={id:t.id,topic:e,request:{method:t.method,params:t.params||null},chainId:i};this.records.set(s.id,s),this.events.emit(Ip,s)},this.resolve=async e=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:e}),!this.records.has(e.id))return;const t=await this.getRecord(e.id);typeof t.response>"u"&&(t.response=Qn(e)?{error:e.error}:{result:e.result},this.records.set(t.id,t),this.events.emit(Op,t))},this.get=async(e,t)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:e,id:t}),await this.getRecord(t)),this.delete=(e,t)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:t}),this.values.forEach((i=>{if(i.topic===e){if(typeof t<"u"&&i.id!==t)return;this.records.delete(i.id),this.events.emit(Np,i)}}))},this.exists=async(e,t)=>(this.isInitialized(),!!this.records.has(t)&&(await this.getRecord(t)).topic===e),this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.logger=Le.generateChildLogger(t,this.name)}get context(){return Le.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach((t=>{if(typeof t.response<"u")return;const i={topic:t.topic,request:Dn(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(i)})),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const t=this.records.get(e);if(!t){const{message:t}=iu("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Pp)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:e}=iu("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}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(Ip,(e=>{const t=Ip;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e}),this.persist()})),this.events.on(Op,(e=>{const t=Op;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e}),this.persist()})),this.events.on(Np,(e=>{const t=Np;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e}),this.persist()}))}isInitialized(){if(!this.initialized){const{message:e}=iu("NOT_INITIALIZED",this.name);throw new Error(e)}}}class lg extends Gh{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.expirations=new Map,this.events=new O.EventEmitter,this.name="expirer",this.version="0.3",this.cached=[],this.initialized=!1,this.storagePrefix=Xd,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(
2),this.cached.forEach((e=>this.expirations.set(e.target,e))),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=e=>{try{const t=this.formatTarget(e);return typeof this.getExpiration(t)<"u"}catch{return!1}},this.set=(e,t)=>{this.isInitialized();const i=this.formatTarget(e),s={target:i,expiry:t};this.expirations.set(i,s),this.checkExpiry(i,s),this.events.emit(Rp,{target:i,expiration:s})},this.get=e=>{this.isInitialized();const t=this.formatTarget(e);return this.getExpiration(t)},this.del=e=>{if(this.isInitialized(),this.has(e)){const t=this.formatTarget(e),i=this.getExpiration(t);this.expirations.delete(t),this.events.emit(Tp,{target:t,expiration:i})}},this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.logger=Le.generateChildLogger(t,this.name)}get context(){return Le.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+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("string"==typeof e)return function(e){return kl("topic",e)}(e);if("number"==typeof e)return function(e){return kl("id",e)}(e);const{message:t}=iu("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(Ap)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:e}=iu("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}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:t}=iu("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(t),new Error(t)}return t}checkExpiry(e,t){const{expiry:i}=t;W.toMiliseconds(i)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(xp,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach(((e,t)=>this.checkExpiry(t,e)))}registerEventListeners(){this.core.heartbeat.on(B.HEARTBEAT_EVENTS.pulse,(()=>this.checkExpirations())),this.events.on(Rp,(e=>{const t=Rp;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})),this.events.on(xp,(e=>{const t=xp;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})),this.events.on(Tp,(e=>{const t=Tp;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}))}isInitialized(){if(!this.initialized){const{message:e}=iu("NOT_INITIALIZED",this.name);throw new Error(e)}}}class ug extends Wh{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,this.name=Cp,this.initialized=!1,this.init=async e=>{Rl()||!Tl()||(this.verifyUrl=(null===e||void 0===e?void 0:e.verifyUrl)||Lp,await this.createIframe())},this.register=async e=>{var t;this.initialized||await this.init(),this.iframe&&(null==(t=this.iframe.contentWindow)||t.postMessage(e.attestationId,this.verifyUrl),this.logger.info(`postMessage sent: ${e.attestationId} ${this.verifyUrl}`))},this.resolve=async e=>{var t;if(this.isDevEnv)return"";this.logger.info(`resolving attestation: ${e.attestationId}`);const i=this.startAbortTimer(W.FIVE_SECONDS),s=await fetch(`${this.verifyUrl}/attestation/${e.attestationId}`,{signal:this.abortController.signal});return clearTimeout(i),200===s.status?null==(t=await s.json())?void 0:t.origin:""},this.createIframe=async()=>{try{await Promise.race([new Promise(((e,t)=>{if(document.getElementById(Cp))return e();const i=document.createElement("iframe");i.setAttribute("id",Cp),i.setAttribute("src",`${this.verifyUrl}/${this.projectId}`),i.style.display="none",i.addEventListener("load",(()=>{this.initialized=!0,e()})),i.addEventListener("error",(e=>{t(e)})),document.body.append(i),this.iframe=i})),new Promise((e=>{setTimeout((()=>
2e("iframe load timeout")),W.toMiliseconds(W.ONE_SECOND/2))}))])}catch(e){this.logger.error(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.error(e)}},this.logger=Le.generateChildLogger(t,this.name),this.verifyUrl=Lp,this.abortController=new AbortController,this.isDevEnv=Pl()&&{NODE_ENV:"production",PUBLIC_URL:"",WDS_SOCKET_HOST:void 0,WDS_SOCKET_PATH:void 0,WDS_SOCKET_PORT:void 0,FAST_REFRESH:!0}.IS_VITEST}get context(){return Le.getLoggerContext(this.logger)}startAbortTimer(e){return setTimeout((()=>this.abortController.abort()),W.toMiliseconds(e))}}var dg=Object.defineProperty,pg=Object.getOwnPropertySymbols,gg=Object.prototype.hasOwnProperty,fg=Object.prototype.propertyIsEnumerable,yg=(e,t,i)=>t in e?dg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,mg=(e,t)=>{for(var i in t||(t={}))gg.call(t,i)&&yg(e,i,t[i]);if(pg)for(var i of pg(t))fg.call(t,i)&&yg(e,i,t[i]);return e};const wg=class e extends qh{constructor(e){super(e),this.protocol="wc",this.version=2,this.name=Qd,this.events=new O.EventEmitter,this.initialized=!1,this.on=(e,t)=>this.events.on(e,t),this.once=(e,t)=>this.events.once(e,t),this.off=(e,t)=>this.events.off(e,t),this.removeListener=(e,t)=>this.events.removeListener(e,t),this.projectId=null===e||void 0===e?void 0:e.projectId,this.relayUrl=(null===e||void 0===e?void 0:e.relayUrl)||rp;const t=typeof(null===e||void 0===e?void 0:e.logger)<"u"&&"string"!=typeof(null===e||void 0===e?void 0:e.logger)?e.logger:Le.pino(Le.getDefaultLoggerOptions({level:(null===e||void 0===e?void 0:e.logger)||Zd}));this.logger=Le.generateChildLogger(t,this.name),this.heartbeat=new B.HeartBeat,this.crypto=new Mp(this,this.logger,null===e||void 0===e?void 0:e.keychain),this.history=new hg(this,this.logger),this.expirer=new lg(this,this.logger),this.storage=null!=e&&e.storage?e.storage:new F(mg(mg({},ep),null===e||void 0===e?void 0:e.storageOptions)),this.relayer=new eg({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new cg(this,this.logger),this.verify=new ug(this.projectId||"",this.logger)}static async init(t){const i=new e(t);return await i.initialize(),i}get context(){return Le.getLoggerContext(this.logger)}async start(){this.initialized||await this.initialize()}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.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}}},vg="client",bg=`wc@2:${vg}:`,_g=vg,Eg="error",Sg=W.SEVEN_DAYS,Ig={wc_sessionPropose:{req:{ttl:W.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:W.FIVE_MINUTES,prompt:!1,tag:1101}},wc_sessionSettle:{req:{ttl:W.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:W.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:W.ONE_DAY,prompt:!1,tag:1104},res:{ttl:W.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:W.ONE_DAY,prompt:!1,tag:1106},res:{ttl:W.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:W.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:W.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:W.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:W.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:W.ONE_DAY,prompt:!1,tag:1112},res:{ttl:W.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:W.THIRTY_SECONDS,prompt:!1,tag:1114},res:{ttl:W.THIRTY_SECONDS,prompt:!1,tag:1115}}},Og={min:W.FIVE_MINUTES,max:W.SEVEN_DAYS},Ng=["wc_sessionPropose","wc_sessionRequest","wc_authRequest"];var Pg=Object.defineProperty,Rg=Object.defineProperties,Tg=Object.getOwnPropertyDescriptors,xg=Object.getOwnPropertySymbols,Ag=Object.prototype.hasOwnProperty,Cg=Object.prototype.propertyIsEnumerable,Lg=(e,t,i)=>t in e?Pg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,Ug=(e,t)=>{for(var i in t||(t={}))Ag.call(t,i)&&Lg(e,i,t[i]);if(xg)for(var i of xg(t))Cg.call(t,i)&&Lg(e,i,t[i]);return e},Mg=(e,t)=>Rg(e,Tg(t));class Dg extends Jh{constructor(e){var t;super(e),t=this,this.name="engine",this.events=new N,this.initialized=!1,this.ignoredPayloadTypes=[ol],this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.client.core.pairing.register({methods:Object.keys(Ig)}),this.initialized=!0)},this.connect=async e=>{this.isInitialized();const t=Mg(Ug({},e),{requiredNamespaces:e.requiredNamespaces||{},optionalNamespaces:e.optionalNamespaces||{}});await this.isValidConnect(t);const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:r,sessionProperties:n,relays:o}=t;let a,c=i,h=!1;if(c&&(h=this.client.core.pairing.pairings.get(c).active),!c||!h){const{topic:e,uri:t}=await this.client.core.pairing.create();c=e,a=t}const l=await this.client.core.crypto.generateKeyPair(),u=Ug({requiredNamespaces:s,optionalNamespaces:r,relays:null!==o&&void 0!==o?o:[{protocol:"irn"}],proposer:{publicKey:l,metadata:this.client.metadata}},n&&{sessionProperties:n}),{reject:d,resolve:p,done:g}=Dl(W.FIVE_MINUTES,"Proposal expired");if(this.events.once(Kl("session_connect"),(async e=>{let{error:t,session:i}=e;if(t)d(t);else if(i){i.self.publicKey=l;const e=Mg(Ug({},i),{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces});await this.client.session.set(i.topic,e),await this.setExpiry(i.topic,i.expiry),c&&await this.client.core.pairing.updateMetadata({topic:c,metadata:i.peer.metadata}),p(e)}})),!c){const{message:e}=iu("NO_MATCHING_KEY",`connect() pairing topic: ${c}`);throw new Error(e)}const f=await this.sendRequest(c,"wc_sessionPropose",u),y=ql(W.FIVE_MINUTES);return await this.setProposal(f,Ug({id:f,expiry:y},u)),{uri:a,approval:g}},this.pair=async e=>(this.isInitialized(),await this.client.core.pairing.pair(e)),this.approve=async e=>{this.isInitialized(),await this.isValidApprove(e);const{id:t,relayProtocol:i,namespaces:s,sessionProperties:r}=e,n=this.client.proposal.get(t);let{pairingTopic:o,proposer:a,requiredNamespaces:c,optionalNamespaces:h}=n;o=o||"",nu(c)||(c=function(e,t){const i=gu(e,t);if(i)throw new Error(i.message);const s={};for(const[r,n]of Object.entries(e))s[r]={methods:n.methods,events:n.events,chains:n.accounts.map((e=>`${e.split(":")[0]}:${e.split(":")[1]}`))};return s}(s,"approve()"));const l=await this.client.core.crypto.generateKeyPair(),u=a.publicKey,d=await this.client.core.crypto.generateSharedKey(l,u);o&&t&&(await this.client.core.pairing.updateMetadata({topic:o,metadata:a.metadata}),await this.sendResult(t,o,{relay:{protocol:null!==i&&void 0!==i?i:"irn"},responderPublicKey:l}),await this.client.proposal.delete(t,su("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:o}));const p=Ug({relay:{protocol:null!==i&&void 0!==i?i:"irn"},namespaces:s,requiredNamespaces:c,optionalNamespaces:h,pairingTopic:o,controller:{publicKey:l,metadata:this.client.metadata},expiry:ql(Sg)},r&&{sessionProperties:r});await this.client.core.relayer.subscribe(d),await this.sendRequest(d,"wc_sessionSettle",p);const g=Mg(Ug({}
2,p),{topic:d,pairingTopic:o,acknowledged:!1,self:p.controller,peer:{publicKey:a.publicKey,metadata:a.metadata},controller:l});return await this.client.session.set(d,g),await this.setExpiry(d,ql(Sg)),{topic:d,acknowledged:()=>new Promise((e=>setTimeout((()=>e(this.client.session.get(d))),500)))}},this.reject=async e=>{this.isInitialized(),await this.isValidReject(e);const{id:t,reason:i}=e,{pairingTopic:s}=this.client.proposal.get(t);s&&(await this.sendError(t,s,i),await this.client.proposal.delete(t,su("USER_DISCONNECTED")))},this.update=async e=>{this.isInitialized(),await this.isValidUpdate(e);const{topic:t,namespaces:i}=e,s=await this.sendRequest(t,"wc_sessionUpdate",{namespaces:i}),{done:r,resolve:n,reject:o}=Dl();return this.events.once(Kl("session_update",s),(e=>{let{error:t}=e;t?o(t):n()})),await this.client.session.update(t,{namespaces:i}),{acknowledged:r}},this.extend=async e=>{this.isInitialized(),await this.isValidExtend(e);const{topic:t}=e,i=await this.sendRequest(t,"wc_sessionExtend",{}),{done:s,resolve:r,reject:n}=Dl();return this.events.once(Kl("session_extend",i),(e=>{let{error:t}=e;t?n(t):r()})),await this.setExpiry(t,ql(Sg)),{acknowledged:s}},this.request=async e=>{this.isInitialized(),await this.isValidRequest(e);const{chainId:t,request:i,topic:s,expiry:r}=e,n=await this.sendRequest(s,"wc_sessionRequest",{request:i,chainId:t},r),{done:o,resolve:a,reject:c}=Dl(r);return this.events.once(Kl("session_request",n),(e=>{let{error:t,result:i}=e;t?c(t):a(i)})),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:t,id:n}),await o()},this.respond=async e=>{this.isInitialized(),await this.isValidRespond(e);const{topic:t,response:i}=e,{id:s}=i;Jn(i)?await this.sendResult(s,t,i.result):Qn(i)&&await this.sendError(s,t,i.error),this.deletePendingSessionRequest(e.response.id,{message:"fulfilled",code:0})},this.ping=async e=>{this.isInitialized(),await this.isValidPing(e);const{topic:t}=e;if(this.client.session.keys.includes(t)){const e=await this.sendRequest(t,"wc_sessionPing",{}),{done:i,resolve:s,reject:r}=Dl();this.events.once(Kl("session_ping",e),(e=>{let{error:t}=e;t?r(t):s()})),await i()}else this.client.core.pairing.pairings.keys.includes(t)&&await this.client.core.pairing.ping({topic:t})},this.emit=async e=>{this.isInitialized(),await this.isValidEmit(e);const{topic:t,event:i,chainId:s}=e;await this.sendRequest(t,"wc_sessionEvent",{event:i,chainId:s})},this.disconnect=async e=>{this.isInitialized(),await this.isValidDisconnect(e);const{topic:t}=e;this.client.session.keys.includes(t)?(await this.sendRequest(t,"wc_sessionDelete",su("USER_DISCONNECTED")),await this.deleteSession(t)):await this.client.core.pairing.disconnect({topic:t})},this.find=e=>(this.isInitialized(),this.client.session.getAll().filter((t=>function(e,t){const{requiredNamespaces:i}=t,s=Object.keys(e.namespaces),r=Object.keys(i);let n=!0;return!!Ll(r,s)&&(s.forEach((t=>{const{accounts:s,methods:r,events:o}=e.namespaces[t],a=Zl(s),c=i[t];(!Ll(el(t,c),a)||!Ll(c.methods,r)||!Ll(c.events,o))&&(n=!1)})),n)}(t,e)))),this.getPendingSessionRequests=()=>(this.isInitialized(),this.client.pendingRequest.getAll()),this.cleanupDuplicatePairings=async e=>{try{const t=this.client.core.pairing.pairings.get(e.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter((i=>{var s,r;return(null==(s=i.peerMetadata)?void 0:s.url)&&(null==(r=i.peerMetadata)?void 0:r.url)===e.self.metadata.url&&i.topic!==t.topic}));if(0===i.length)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map((e=>this.client.core.pairing.disconnect({topic:e.topic})))),this.client.logger.info("Duplicate pairings clean up finished")}catch(t){this.client.logger.error(t)}},this.deleteSession=async(e,t)=>{const{self:i}=this.client.session.get(e);await this.client.core.relayer.unsubscribe(e),await Promise.all([this.client.session.delete(e,su("USER_DISCONNECTED")),this.client.core.crypto.deleteKeyPair(i.publicKey),this.client.core.crypto.deleteSymKey(e),t?Promise.resolve():this.client.core.expirer.del(e)])},this.deleteProposal=async(e,t)=>{await Promise.all([this.client.proposal.delete(e,su("USER_DISCONNECTED")),t?Promise.resolve():this.client.core.expirer.del(e)])},this.deletePendingSessionRequest=async function(e,i){let s=arguments.length>2&&void 0!==arguments[2]&&arguments[2];
2await Promise.all([t.client.pendingRequest.delete(e,i),s?Promise.resolve():t.client.core.expirer.del(e)])},this.setExpiry=async(e,t)=>{this.client.session.keys.includes(e)&&await this.client.session.update(e,{expiry:t}),this.client.core.expirer.set(e,t)},this.setProposal=async(e,t)=>{await this.client.proposal.set(e,t),this.client.core.expirer.set(e,t.expiry)},this.setPendingSessionRequest=async e=>{const t=Ig.wc_sessionRequest.req.ttl,{id:i,topic:s,params:r}=e;await this.client.pendingRequest.set(i,{id:i,topic:s,params:r}),t&&this.client.core.expirer.set(i,ql(t))},this.sendRequest=async(e,t,i,s)=>{const r=Dn(t,i);if(Tl()&&Ng.includes(t)){const e=dl(JSON.stringify(r));await this.client.core.verify.register({attestationId:e})}const n=await this.client.core.crypto.encode(e,r),o=Ig[t].req;return s&&(o.ttl=s),this.client.core.history.set(e,r),this.client.core.relayer.publish(e,n,o),r.id},this.sendResult=async(e,t,i)=>{const s=jn(e,i),r=await this.client.core.crypto.encode(t,s),n=await this.client.core.history.get(t,e),o=Ig[n.request.method].res;this.client.core.relayer.publish(t,r,o),await this.client.core.history.resolve(s)},this.sendError=async(e,t,i)=>{const s=kn(e,i),r=await this.client.core.crypto.encode(t,s),n=await this.client.core.history.get(t,e),o=Ig[n.request.method].res;this.client.core.relayer.publish(t,r,o),await this.client.core.history.resolve(s)},this.cleanup=async()=>{const e=[],t=[];this.client.session.getAll().forEach((t=>{$l(t.expiry)&&e.push(t.topic)})),this.client.proposal.getAll().forEach((e=>{$l(e.expiry)&&t.push(e.id)})),await Promise.all([...e.map((e=>this.deleteSession(e))),...t.map((e=>this.deleteProposal(e)))])},this.onRelayEventRequest=e=>{const{topic:t,payload:i}=e,s=i.method;switch(s){case"wc_sessionPropose":return this.onSessionProposeRequest
2(t,i);case"wc_sessionSettle":return this.onSessionSettleRequest(t,i);case"wc_sessionUpdate":return this.onSessionUpdateRequest(t,i);case"wc_sessionExtend":return this.onSessionExtendRequest(t,i);case"wc_sessionPing":return this.onSessionPingRequest(t,i);case"wc_sessionDelete":return this.onSessionDeleteRequest(t,i);case"wc_sessionRequest":return this.onSessionRequest(t,i);case"wc_sessionEvent":return this.onSessionEventRequest(t,i);default:return this.client.logger.info(`Unsupported request method ${s}`)}},this.onRelayEventResponse=async e=>{const{topic:t,payload:i}=e,s=(await this.client.core.history.get(t,i.id)).request.method;switch(s){case"wc_sessionPropose":return this.onSessionProposeResponse(t,i);case"wc_sessionSettle":return this.onSessionSettleResponse(t,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(t,i);case"wc_sessionExtend":return this.onSessionExtendResponse(t,i);case"wc_sessionPing":return this.onSessionPingResponse(t,i);case"wc_sessionRequest":return this.onSessionRequestResponse(t,i);default:return this.client.logger.info(`Unsupported response method ${s}`)}},this.onSessionProposeRequest=async(e,t)=>{const{params:i,id:s}=t;try{this.isValidConnect(Ug({},t.params));const r=ql(W.FIVE_MINUTES),n=Ug({id:s,pairingTopic:e,expiry:r},i);await this.setProposal(s,n);const o=dl(JSON.stringify(t)),a=await this.getVerifyContext(o,n.proposer.metadata);this.client.events.emit("session_proposal",{id:s,params:n,verifyContext:a})}catch(r){await this.sendError(s,e,r),this.client.logger.error(r)}},this.onSessionProposeResponse=async(e,t)=>{const{id:i}=t;if(Jn(t)){const{result:s}=t;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:s});const r=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:r});const n=r.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:n});const o=s.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:o});const a=await this.client.core.crypto.generateSharedKey(n,o);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:a});const c=await this.client.core.relayer.subscribe(a);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:c}),await this.client.core.pairing.activate({topic:e})}else Qn(t)&&(await this.client.proposal.delete(i,su("USER_DISCONNECTED")),this.events.emit(Kl("session_connect"),{error:t.error}))},this.onSessionSettleRequest=async(e,t)=>{const{id:i,params:s}=t;try{this.isValidSessionSettleRequest(s);const{relay:i,controller:r,expiry:n,namespaces:o,requiredNamespaces:a,optionalNamespaces:c,sessionProperties:h,pairingTopic:l}=t.params,u=Ug({topic:e,relay:i,expiry:n,namespaces:o,acknowledged:!0,pairingTopic:l,requiredNamespaces:a,optionalNamespaces:c,controller:r.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:r.publicKey,metadata:r.metadata}},h&&{sessionProperties:h});await this.sendResult(t.id,e,!0),this.events.emit(Kl("session_connect"),{session:u}),this.cleanupDuplicatePairings(u)}catch(r){await this.sendError(i,e,r),this.client.logger.error(r)}},this.onSessionSettleResponse=async(e,t)=>{const{id:i}=t;Jn(t)?(await this.client.session.update(e,{acknowledged:!0}),this.events.emit(Kl("session_approve",i),{})):Qn(t)&&(await this.client.session.delete(e,su("USER_DISCONNECTED")),this.events.emit(Kl("session_approve",i),{error:t.error}))},this.onSessionUpdateRequest=async(e,t)=>{const{params:i,id:s}=t;try{this.isValidUpdate(Ug({topic:e},i)),await this.client.session.update(e,{namespaces:i.namespaces}),await this.sendResult(s,e,!0),this.client.events.emit("session_update",{id:s,topic:e,params:i})}catch(r){await this.sendError(s,e,r),this.client.logger.error(r)}},this.onSessionUpdateResponse=(e,t)=>{const{id:i}=t;Jn(t)?this.events.emit(Kl("session_update",i),{}):Qn(t)&&this.events.emit(Kl("session_update",i),{error:t.error})},this.onSessionExtendRequest=async(e,t)=>{const{id:i}=t;try{this.isValidExtend({topic:e}),await this.setExpiry(e,ql(Sg)),await this.sendResult(i,e,!0),this.client.events.emit("session_extend",{id:i,topic:e})}catch(s){await this.sendError(i,e,s),this.client.logger.error(s)}},this.onSessionExtendResponse=(e,t)=>{const{id:i}=t;Jn(t)?this.events.emit(Kl("session_extend",i),{}):Qn(t)&&this.events.emit(Kl("session_extend",i),{error:t.error})},this.onSessionPingRequest=async(e,t)=>{const{id:i}=t;try{this.isValidPing({topic:e}),await this.sendResult(i,e,!0),this.client.events.emit("session_ping",{id:i,topic:e})}catch(s){await this.sendError(i,e,s),this.client.logger.error(s)}},this.onSessionPingResponse=(e,t)=>{const{id:i}=t;setTimeout((()=>{Jn(t)?this.events.emit(Kl("session_ping",i),{}):Qn(t)&&this.events.emit(Kl("session_ping",i),{error:t.error})}),500)},this.onSessionDeleteRequest=async(e,t)=>{const{id:i}=t;try{this.isValidDisconnect({topic:e,reason:t.params}),await Promise.all([new Promise((t=>{this.client.core.relayer.once(dp,(async()=>{t(await this.deleteSession(e))}))})),this.sendResult(i,e,!0)]),this.client.events.emit("session_delete",{id:i,topic:e})}catch(s){await this.sendError(i,e,s),this.client.logger.error(s)}},this.onSessionRequest=async(e,t)=>{const{id:i,params:s}=t;try{this.isValidRequest(Ug({topic:e},s)),await this.setPendingSessionRequest({id:i,topic:e,params:s});const r=dl(JSON.stringify(t)),n=this.client.session.get(e),o=await this.getVerifyContext(r,n.peer.metadata);this.client.events.emit("session_request",{id:i,topic:e,params:s,verifyContext:o})}catch(r){await this.sendError(i,e,r),this.client.logger.error(r)}},this.onSessionRequestResponse=(e,t)=>{const{id:i}=t;Jn(t)?this.events.emit(Kl("session_request",i),{result:t.result}):Qn(t)&&this.events.emit(Kl("session_request",i),{error:t.error})},this.onSessionEventRequest=async(e,t)=>{const{id:i,params:s}=t;try{this.isValidEmit(Ug({topic:e},s)),this.client.events.emit("session_event",{id:i,topic:e,params:s})}catch(r){await this.sendError(i,e,r),this.client.logger.error(r)}},this.isValidConnect=async e=>{if(!yu(e)){const{message:t}=iu("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(e)}`);throw new Error(t)}const{pairingTopic:t,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:r,relays:n}=e;if(ou(t)||await this.isValidPairingTopic(t),!function(e,t){let i=!1;return t&&!e?i=!0:e&&ru(e)&&e.length&&e.forEach((e=>{i=fu(e)})),i}(n,!0)){const{message:e}=iu("MISSING_OR_INVALID",`connect() relays: ${n}`);throw new Error(e)}!ou(i)&&0!==nu(i)&&this.validateNamespaces(i,"requiredNamespaces"),!ou(s)&&0!==nu(s)&&this.validateNamespaces(s,"optionalNamespaces"),ou(r)||this.validateSessionProps(r,"sessionProperties")},this.validateNamespaces=(e,t)=>{const i=function(e,t,i){let s=null;if(e&&nu(e)){const i=pu(e,t);i&&(s=i);const r=uu(e,t);r&&(s=r)}else s=iu("MISSING_OR_INVALID",`${t}, ${i} should be an object with data`);return s}(e,"connect()",t);if(i)throw new Error(i.message)},this.isValidApprove=async e=>{if(!yu(e))throw new Error(iu("MISSING_OR_INVALID",`approve() params: ${e}`).message);const{id:t,namespaces:i,relayProtocol:s,sessionProperties:r}=e;await this.isValidProposalId(t);const n=this.client.proposal.get(t),o=gu(i,"approve()");if(o)throw new Error(o.message);const a=bu(n.requiredNamespaces,i,"approve()");if(a)throw new Error(a.message);if(!au(s,!0)){const{message:e}=iu("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(e)}ou(r)||this.validateSessionProps(r,"sessionProperties")},this.isValidReject=async e=>{if(!yu(e)){const{message:t}=iu("MISSING_OR_INVALID",`reject() params: ${e}`);throw new Error(t)}const{id:t,reason:i}=e;if(await this.isValidProposalId(t),!function(e){return!(!e||"object"!=typeof e||!e.code||!cu(e.code,!1)||
2!e.message||!au(e.message,!1))}(i)){const{message:e}=iu("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(e)}},this.isValidSessionSettleRequest=e=>{if(!yu(e)){const{message:t}=iu("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${e}`);throw new Error(t)}const{relay:t,controller:i,namespaces:s,expiry:r}=e;if(!fu(t)){const{message:e}=iu("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(e)}const n=function(e,t){let i=null;return au(null===e||void 0===e?void 0:e.publicKey,!1)||(i=iu("MISSING_OR_INVALID",`${t} controller public key should be a string`)),i}(i,"onSessionSettleRequest()");if(n)throw new Error(n.message);const o=gu(s,"onSessionSettleRequest()");if(o)throw new Error(o.message);if($l(r)){const{message:e}=iu("EXPIRED","onSessionSettleRequest()");throw new Error(e)}},this.isValidUpdate=async e=>{if(!yu(e)){const{message:t}=iu("MISSING_OR_INVALID",`update() params: ${e}`);throw new Error(t)}const{topic:t,namespaces:i}=e;await this.isValidSessionTopic(t);const s=this.client.session.get(t),r=gu(i,"update()");if(r)throw new Error(r.message);const n=bu(s.requiredNamespaces,i,"update()");if(n)throw new Error(n.message)},this.isValidExtend=async e=>{if(!yu(e)){const{message:t}=iu("MISSING_OR_INVALID",`extend() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidSessionTopic(t)},this.isValidRequest=async e=>{if(!yu(e)){const{message:t}=iu("MISSING_OR_INVALID",`request() params: ${e}`);throw new Error(t)}const{topic:t,request:i,chainId:s,expiry:r}=e;await this.isValidSessionTopic(t);const{namespaces:n}=this.client.session.get(t);if(!mu(n,s)){const{message:e}=iu("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(e)}if(!function(e){return!(ou(e)||!au(e.method,!1))}(i)){const{message:e}=iu("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(e)}if(!wu(n,s,i.method)){const{message:e}=iu("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(e)}if(r&&!function(e,t){return cu(e,!1)&&e<=t.max&&e>=t.min}(r,Og)){const{message:e}=iu("MISSING_OR_INVALID",`request() expiry: ${r}. Expiry must be a number (in seconds) between ${Og.min} and ${Og.max}`);throw new Error(e)}},this.isValidRespond=async e=>{if(!yu(e)){const{message:t}=iu("MISSING_OR_INVALID",`respond() params: ${e}`);throw new Error(t)}const{topic:t,response:i}=e;if(await this.isValidSessionTopic(t),!function(e){return!(ou(e)||ou(e.result)&&ou(e.error)||!cu(e.id,!1)||!au(e.jsonrpc,!1))}(i)){const{message:e}=iu("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(i)}`);throw new Error(e)}},this.isValidPing=async e=>{if(!yu(e)){const{message:t}=iu("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)},this.isValidEmit=async e=>{if(!yu(e)){const{message:t}=iu("MISSING_OR_INVALID",`emit() params: ${e}`);throw new Error(t)}const{topic:t,event:i,chainId:s}=e;await this.isValidSessionTopic(t);const{namespaces:r}=this.client.session.get(t);if(!mu(r,s)){const{message:e}=iu("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(e)}if(!function(e){return!(ou(e)||!au(e.name,!1))}(i)){const{message:e}=iu("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(e)}if(!vu(r,s,i.name)){const{message:e}=iu("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(e)}},this.isValidDisconnect=async e=>{if(!yu(e)){const{message:t}=iu("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)},this.getVerifyContext=async(e,t)=>{const i={verified:{verifyUrl:t.verifyUrl||"",validation:"UNKNOWN",origin:t.url||""}};try{const s=await this.client.core.verify.resolve({attestationId:e,verifyUrl:t.verifyUrl});s&&(i.verified.origin=s,i.verified.validation=s===t.url?"VALID":"INVALID")}catch(s){this.client.logger.error(s)}return this.client.logger.info(`Verify context: ${JSON.stringify(i)}`),i},this.validateSessionProps=(e,t)=>{Object.values(e).forEach((e=>{if(!au(e,!1)){const{message:i}=iu("MISSING_OR_INVALID",`${t} must be in Record<string, string> format. Received: ${JSON.stringify(e)}`);throw new Error(i)}}))}}isInitialized(){if(!this.initialized){const{message:e}=iu("NOT_INITIALIZED",this.name);throw new Error(e)}}
2registerRelayerEvents(){this.client.core.relayer.on(np,(async e=>{const{topic:t,message:i}=e;if(this.ignoredPayloadTypes.includes(this.client.core.crypto.getPayloadType(i)))return;const s=await this.client.core.crypto.decode(t,i);Wn(s)?(this.client.core.history.set(t,s),this.onRelayEventRequest({topic:t,payload:s})):Yn(s)&&(await this.client.core.history.resolve(s),this.onRelayEventResponse({topic:t,payload:s}))}))}registerExpirerEvents(){this.client.core.expirer.on(xp,(async e=>{const{topic:t,id:i}=zl(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,iu("EXPIRED"),!0);t?this.client.session.keys.includes(t)&&(await this.deleteSession(t,!0),this.client.events.emit("session_expire",{topic:t})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))}))}isValidPairingTopic(e){if(!au(e,!1)){const{message:t}=iu("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}=iu("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if($l(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=iu("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!au(e,!1)){const{message:t}=iu("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(t)}if(!this.client.session.keys.includes(e)){const{message:t}=iu("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if($l(this.client.session.get(e).expiry)){await this.deleteSession(e);const{message:t}=iu("EXPIRED",`session topic: ${e}`);throw new Error(t)}}async isValidSessionOrPairingTopic(e){if(this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else{if(!this.client.core.pairing.pairings.keys.includes(e)){if(au(e,!1)){const{message:t}=iu("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}{const{message:t}=iu("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}this.isValidPairingTopic(e)}}async isValidProposalId(e){if(!function(e){return"number"==typeof e}(e)){const{message:t}=iu("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=iu("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if($l(this.client.proposal.get(e).expiry)){await this.deleteProposal(e);const{message:t}=iu("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}}class jg extends ag{constructor(e,t){super(e,t,"proposal",bg),this.core=e,this.logger=t}}class kg extends ag{constructor(e,t){super(e,t,"session",bg),this.core=e,this.logger=t}}class zg extends ag{constructor(e,t){super(e,t,"request",bg,(e=>e.id)),this.core=e,this.logger=t}}class qg extends Yh{constructor(e){super(e),this.protocol="wc",this.version=2,this.name=_g,this.events=new O.EventEmitter,this.on=(e,t)=>this.events.on(e,t),this.once=(e,t)=>this.events.once(e,t),this.off=(e,t)=>this.events.off(e,t),this.removeListener=(e,t)=>this.events.removeListener(e,t),this.removeAllListeners=e=>this.events.removeAllListeners(e),this.connect=async e=>{try{return await this.engine.connect(e)}catch(t){throw this.logger.error(t.message),t}},this.pair=async e=>{try{return await this.engine.pair(e)}catch(t){throw this.logger.error(t.message),t}},this.approve=async e=>{try{return await this.engine.approve(e)}catch(t){throw this.logger.error(t.message),t}},this.reject=async e=>{try{return await this.engine.reject(e)}catch(t){throw this.logger.error(t.message),t}},this.update=async e=>{try{return await this.engine.update(e)}catch(t){throw this.logger.error(t.message),t}},this.extend=async e=>{try{return await this.engine.extend(e)}catch(t){throw this.logger.error(t.message),t}},this.request=async e=>{try{return await this.engine.request(e)}catch(t){throw this.logger.error(t.message),t}},this.respond=async e=>{try{return await this.engine.respond(e)}catch(t){throw this.logger.error(t.message),t}},this.ping=async e=>{try{return await this.engine.ping(e)}catch(t){throw this.logger.error(t.message),t}},this.emit=async e=>{try{return await this.engine.emit(e)}catch(t){throw this.logger.error(t.message),t}},this.disconnect=async e=>{try{return await this.engine.disconnect(e)}catch(t){throw this.logger.error(t.message),t}},this.find=e=>{try{return this.engine.find(e)}catch(t){throw this.logger.error(t.message),t}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(e){throw this.logger.error(e.message),e}},this.name=(null===e||void 0===e?void 0:e.name)||_g,this.metadata=(null===e||void 0===e?void 0:e.metadata)||Ls()||{name:"",description:"",url:"",icons:[""]};const t=typeof(null===e||void 0===e?void 0:e.logger)<"u"&&"string"!=typeof(null===e||void 0===e?void 0:e.logger)?e.logger:Le.pino(Le.getDefaultLoggerOptions({level:(null===e||void 0===e?void 0:e.logger)||Eg}));this.core=(null===e||void 0===e?void 0:e.core)||new wg(e),this.logger=Le.generateChildLogger(t,this.name),this.session=new kg(this.core,this.logger),this.proposal=new jg(this.core,this.logger),this.pendingRequest=new zg(this.core,this.logger),this.engine=new Dg(this)}static async init(e){const t=new qg(e);return await t.initialize(),t}get context(){return Le.getLoggerContext(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.engine.init(),this.core.verify.init({verifyUrl:this.metadata.verifyUrl}),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}const $g="signer_init",Kg="signer_uri",Vg="signer_created",Hg="signer_updated",Fg="signer_deleted",Bg="signer_event";class Gg extends $n{constructor(e){super(),this.events=new O.EventEmitter,this.pending=!1,this.initializing=!1,this.requiredNamespaces=(null===e||void 0===e?void 0:e.requiredNamespaces)||{},this.opts=null===e||void 0===e?void 0:e.client}get connected(){return typeof this.session<"u"}get connecting(){return this.pending}get chains(){return this.session?Zh(this.session.namespaces):function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];const i=[];return Object.keys(e).forEach((s=>{if(t.length&&!t.includes(s))return;const r=e[s];i.push(...el(s,r))})),i}(this.requiredNamespaces)}get accounts(){return this.session?function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];const i=[];return Object.keys(e).forEach((s=>{if(t.length&&!t.includes(s))return;const r=e[s];i.push(...r.accounts)})),i}(this.session.namespaces):[]}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(){if(this.pending)return new Promise(((e,t)=>{this.events.once("open",(()=>{if(this.events.once("open_error",(e=>{t(e)})),typeof this.client>"u")return t(new Error("Sign Client not initialized"));e()}
2))}));try{this.pending=!0;const e=await this.register(),t=e.find({requiredNamespaces:this.requiredNamespaces});if(t.length)return this.onOpen(t[0]);const{uri:i,approval:s}=await e.connect({requiredNamespaces:this.requiredNamespaces});this.events.emit(Kg,{uri:i}),this.session=await s(),this.events.emit(Vg,this.session),this.onOpen()}catch(e){throw this.events.emit("open_error",e),e}}async close(){typeof this.session>"u"||(await(await this.register()).disconnect({topic:this.session.topic,reason:su("USER_DISCONNECTED")}),this.onClose())}async send(e,t){if(typeof this.client>"u"&&(this.client=await this.register(),this.connected||await this.open()),typeof this.session>"u")throw new Error("Signer connection is missing session");this.client.request({topic:this.session.topic,request:e,chainId:null===t||void 0===t?void 0:t.chainId}).then((t=>this.events.emit("payload",jn(e.id,t)))).catch((t=>this.events.emit("payload",kn(e.id,t.message))))}async register(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.opts;if(typeof this.client<"u")return this.client;if(this.initializing)return new Promise(((e,t)=>{this.events.once("register_error",(e=>{t(e)})),this.events.once($g,(()=>{if(typeof this.client>"u")return t(new Error("Sign Client not initialized"));e(this.client)}))}));if(function(e){return typeof e<"u"&&typeof e.context<"u"}(e))return this.client=e,this.registerEventListeners(),this.client;try{return this.initializing=!0,this.client=await qg.init(e),this.initializing=!1,this.registerEventListeners(),this.events.emit($g),this.client}catch(t){throw this.events.emit("register_error",t),t}}onOpen(e){this.pending=!1,e&&(this.session=e),this.events.emit("open")}onClose(){this.pending=!1,this.client&&(this.client=void 0),this.events.emit("close")}registerEventListeners(){typeof this.client<"u"&&(this.client.on("session_event",(e=>{var t;this.session&&(null==(t=this.session)?void 0:t.topic)!==e.topic||this.events.emit(Bg,e.params)})),this.client.on("session_update",(e=>{var t;typeof this.client<"u"&&(this.session&&(null==(t=this.session)?void 0:t.topic)!==e.topic||(this.session=this.client.session.get(e.topic),this.events.emit(Hg,this.session)))})),this.client.on("session_delete",(e=>{var t;this.session&&(this.session&&(null==(t=this.session)?void 0:t.topic)!==e.topic||(this.onClose(),this.events.emit(Fg,this.session),this.session=void 0))})))}}const Wg=":";function Yg(e){const{namespace:t,reference:i}=function(e){const[t,i,s]=e.split(Wg);return{namespace:t,reference:i,address:s}}(e);return function(e){const{namespace:t,reference:i}=e;return[t,i].join(Wg)}({namespace:t,reference:i})}function Jg(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];const i=[];return Object.keys(e).forEach((s=>{if(t.length&&!t.includes(s))return;const r=e[s];i.push(...function(e){return function(e,t){const i=[];return e.forEach((e=>{const s=t(e);i.includes(s)||i.push(s)})),i}(e,Yg)}(r.accounts))})),i}class Qg{constructor(){h(this,"accounts",[]),h(this,"eventEmitter",new O.EventEmitter),h(this,"updateSession",(e=>{if(!this.isValidSession(e))throw console.warn("updateSession incompatible session",e,"for adapter",this.formatChainId(this.chainId)),new Error("Invalid session");this.session=e;const t=Jg(e.namespaces,[this.namespace]);this.setChainIds(t);const i=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];const i=[];return Object.keys(e).forEach((s=>{if(t.length&&!t.includes(s))return;const r=e[s];i.push(...r.accounts)})),i}(e.namespaces,[this.namespace]);this.setAccounts(i)})),h(this,"isValidSession",(e=>{var t,i;let{namespaces:s,requiredNamespaces:r}=e;const n=this.formatChainId(this.chainId);return r?!(null===(t=r[this.namespace])||void 0===t||null===(t=t.chains)||void 0===t||!t.includes(n)):!(null===s||void 0===s||null===(i=s[this.namespace])||void 0===i||!i.accounts.some((e=>e.startsWith(n))))}))}getRequiredNamespaces(){const e=[this.formatChainId(this.chainId)];return{[this.namespace]:{chains:e,methods:this.methods,events:this.events}}}isCompatibleChainId(e){return"string"==typeof e&&e.startsWith(`${this.namespace}:`)}setChainIds(e){const t=e.filter((e=>this.isCompatibleChainId(e))).map((e=>this.parseChainId(e))).filter((e=>e!==this.chainId));t.length&&(this.chainId=t[0],this.eventEmitter.emit("chainChanged",this.chainId))}setChainId(e){if(this.isCompatibleChainId(e)){const t=this.parseChainId(e);this.chainId=t,this.eventEmitter.emit("chainChanged",this.chainId)}}parseAccountId(e){const[t,i,s]=e.split(":");return{chainId:`${t}:${i}`,address:s}}getSignerConnection(e){return new Gg({requiredNamespaces:{[this.namespace]:{chains:this.rpc.chains,methods:this.rpc.methods,events:this.rpc.events}},client:e})}registerEventListeners(){this.rpcProvider.on("connect",(()=>{const{chains:e,accounts:t}=this.signerConnection;null!==e&&void 0!==e&&e.length&&this.setChainIds(e),(null===t||void 0===t?void 0:t.length)&&this.setAccounts(t)})),this.signerConnection.on(Vg,this.updateSession),this.signerConnection.on(Hg,this.updateSession),this.signerConnection.on(Bg,(e=>{if(!this.rpc.chains.includes(e.chainId))return;const{event:t}=e;"accountsChanged"===t.name?(this.accounts=t.data,this.eventEmitter.emit("accountsChanged",this.accounts)):"chainChanged"===t.name?this.setChainId(t.data):this.eventEmitter.emit(t.name,t.data)})),this.rpcProvider.on("disconnect",(()=>{this.eventEmitter.emit("disconnect")}))}}class Xg extends n.gD{constructor(e,t,i,s){super(e,t,i),this.wallet=s}async execute(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return e=Array.isArray(e)?e:[e],await this.wallet.starknet_requestAddInvokeTransaction({accountAddress:this.address,executionRequest:{calls:e,abis:t,invocationDetail
2s:i}})}async declare(e,t){throw new Error("Not supported via Argent Login")}async deployAccount(e,t){throw new Error("Not supported via Argent Login")}}class Zg{constructor(e){this.wallet=e}async getPubKey(){throw new Error("Not supported via Argent Login")}async signMessage(e,t){const{signature:i}=await this.wallet.starknet_signTypedData({accountAddress:t,typedData:e});return i}async signTransaction(e,t,i){throw new Error("Not supported via Argent Login")}async signDeployAccountTransaction(e){throw new Error("Not supported via Argent Login")}async signDeclareTransaction(e){throw new Error("Not supported via Argent Login")}}class ef extends Qg{constructor(e){let{client:t,chainId:i,rpcUrl:s,provider:r}=e;super(),h(this,"id","argentMobile"),h(this,"name","Argent Mobile"),h(this,"version","0.1.0"),h(this,"icon",""),h(this,"provider"),h(this,"signer"),h(this,"account"),h(this,"selectedAddress",""),h(this,"namespace","starknet"),h(this,"methods",["starknet_signTypedData","starknet_requestAddInvokeTransaction"]),h(this,"events",["chainChanged","accountsChanged"]),h(this,"remoteSigner"),h(this,"signerConnection"),h(this,"rpcProvider"),h(this,"chainId"),h(this,"client"),h(this,"session"),h(this,"rpc"),h(this,"walletRpc"),h(this,"on",((e,t)=>{this.eventEmitter.on(e,t)})),h(this,"off",((e,t)=>{this.eventEmitter.off(e,t)})),this.chainId=String(null!==i&&void 0!==i?i:n.AA.NetworkName.SN_MAIN),this.rpc={chains:i?[this.formatChainId(this.chainId)]:[],methods:this.methods,events:this.events},this.signerConnection=this.getSignerConnection(t),this.rpcProvider=new Xn(this.signerConnection),this.client=t,this.registerEventListeners(),this.walletRpc=new Proxy({},{get:(e,t)=>e=>this.requestWallet({method:t,params:e})}),this.remoteSigner=new Zg(this.walletRpc),this.provider=r||new n.bd({nodeUrl:s}),this.account=new Xg(this.provider,"",this.remoteSigner,this.walletRpc)}getNetworkName(e){if("SN_SEPOLIA"===e)return n.AA.NetworkName.SN_SEPOLIA;if("SN_MAIN"===e)return n.AA.NetworkName.SN_MAIN;throw new Error(`Unknown starknet.js network name for chainId ${e}`)}async request(e){throw new Error("Not implemented: .request()")}async enable(){return await this.rpcProvider.connect(),this.accounts}get isConnected(){return!0}async isPreauthorized(){return!!this.client.session.getAll().find(this.isValidSession)}async requestWallet(e){if(!this.session)throw new Error("No session");try{const{topic:t}=this.session,i=this.formatChainId(this.chainId);Dh.showApprovalModal(e);const s=await this.client.request({topic:t,chainId:i,request:e});return Dh.closeModal("animateSuccess"),s}catch(t){throw Dh.closeModal(),t instanceof Error?new Error(t.message):new Error("Unknow error on requestWallet")}}get isConnecting(){return this.signerConnection.connecting}async disable(){await this.rpcProvider.disconnect()}get isWalletConnect(){return!0}registerEventListeners(){super.registerEventListeners(),this.eventEmitter.on("chainChanged",(e=>{throw new Error("Not implemented: chainChanged")}))}formatChainId(e){return`${this.namespace}:${(e=>e.replace(/^SN_/,"SN"))(e)}`}parseChainId(e){return(e=>e.replace(/^SN/,"SN_"))(e.split(":")[1])}setAccounts(e){this.accounts=e.filter((e=>this.parseChainId(this.parseAccountId(e).chainId)===this.chainId)).map((e=>this.parseAccountId(e).address));const{address:t}=this.parseAccountId(e[0]),i=t.startsWith("0x")?t:`0x${t}`;this.account=new Xg(this.provider,i,this.remoteSigner,this.walletRpc),this.eventEmitter.emit("accountsChanged",this.accounts),this.selectedAddress=i}}const tf=async e=>(async(e,t)=>{let{projectId:i,chainId:s,name:r,description:n,rpcUrl:a,bridgeUrl:c=kh(s),mobileUrl:h=zh(s),modalType:l="overlay",url:u,icons:d,walletConnect:p,provider:g}=e;if(!c)throw new Error("bridgeUrl is required");if(!h)throw new Error("mobileUrl is required");Dh.bridgeUrl=c,Dh.mobileUrl=h,Dh.type=l;const f={projectId:i,metadata:{name:null!==r&&void 0!==r?r:"Unknown dapp",description:null!==n&&void 0!==n?n:"Unknown dapp description",url:null!==u&&void 0!==u?u:"#",icons:null!==d&&void 0!==d?d:[],...null===p||void 0===p?void 0:p.metadata}},y=await Ch.init(f),m=new t({client:y,chainId:s,rpcUrl:a,provider:g});y.on("session_event",(e=>{})),y.on("session_update",(e=>{let{topic:t,params:i}=e;const{namespaces:s}=i,r=y.session.get(t);m.updateSession({...r,namespaces:s})})),y.on("session_delete",(()=>{}));try{const e=y.session.getAll().find(m.isValidSession);if(e)return m.updateSession(e),m;const t={requiredNamespaces:m.getRequiredNamespaces()};(0,o.r)(),await new Promise((e=>setTimeout(e,200)));const{uri:i,approval:s}=await y.connect(t);if(i){Dh.showConnectionModal(i),Dh.wcUri=i;const e=await s();m.updateSession(e),Dh.closeModal("animateSuccess")}return m}catch{return console.error("@argent/login::error"),Dh.closeModal(),null}})(e,ef)}}]);
3//# sourceMappingURL=560.a3b61ff6.chunk.js.map

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.