@walletconnect/ethereum-provider 2.13.2 → 2.13.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.es.js +1 -1
- package/dist/index.es.js.map +1 -1
- package/dist/index.umd.js +2 -2
- package/dist/index.umd.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/dist/types/EthereumProvider.d.ts.map +1 -1
- package/package.json +5 -5
package/dist/index.umd.js
CHANGED
|
@@ -40,7 +40,7 @@
|
|
|
40
40
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
41
41
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
42
42
|
PERFORMANCE OF THIS SOFTWARE.
|
|
43
|
-
***************************************************************************** */var Jf=function(t,e){return Jf=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)n.hasOwnProperty(i)&&(r[i]=n[i])},Jf(t,e)};function Cx(t,e){Jf(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var Zf=function(){return Zf=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},Zf.apply(this,arguments)};function Ox(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function Mx(t,e,r,n){var i=arguments.length,o=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,c;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(t,e,r,n);else for(var l=t.length-1;l>=0;l--)(c=t[l])&&(o=(i<3?c(o):i>3?c(e,r,o):c(e,r))||o);return i>3&&o&&Object.defineProperty(e,r,o),o}function Px(t,e){return function(r,n){e(r,n,t)}}function $x(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function Tx(t,e,r,n){function i(o){return o instanceof r?o:new r(function(c){c(o)})}return new(r||(r=Promise))(function(o,c){function l(g){try{h(n.next(g))}catch(_){c(_)}}function f(g){try{h(n.throw(g))}catch(_){c(_)}}function h(g){g.done?o(g.value):i(g.value).then(l,f)}h((n=n.apply(t,e||[])).next())})}function Nx(t,e){var r={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,i,o,c;return c={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(c[Symbol.iterator]=function(){return this}),c;function l(h){return function(g){return f([h,g])}}function f(h){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(o=h[0]&2?i.return:h[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,h[1])).done)return o;switch(i=0,o&&(h=[h[0]&2,o.value]),h[0]){case 0:case 1:o=h;break;case 4:return r.label++,{value:h[1],done:!1};case 5:r.label++,i=h[1],h=[0];continue;case 7:h=r.ops.pop(),r.trys.pop();continue;default:if(o=r.trys,!(o=o.length>0&&o[o.length-1])&&(h[0]===6||h[0]===2)){r=0;continue}if(h[0]===3&&(!o||h[1]>o[0]&&h[1]<o[3])){r.label=h[1];break}if(h[0]===6&&r.label<o[1]){r.label=o[1],o=h;break}if(o&&r.label<o[2]){r.label=o[2],r.ops.push(h);break}o[2]&&r.ops.pop(),r.trys.pop();continue}h=e.call(t,r)}catch(g){h=[6,g],i=0}finally{n=o=0}if(h[0]&5)throw h[1];return{value:h[0]?h[1]:void 0,done:!0}}}function Rx(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function Lx(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function Xf(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function uv(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,o=[],c;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(l){c={error:l}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(c)throw c.error}}return o}function Bx(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(uv(arguments[e]));return t}function Ux(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),i=0,e=0;e<r;e++)for(var o=arguments[e],c=0,l=o.length;c<l;c++,i++)n[i]=o[c];return n}function gc(t){return this instanceof gc?(this.v=t,this):new gc(t)}function Fx(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),i,o=[];return i={},c("next"),c("throw"),c("return"),i[Symbol.asyncIterator]=function(){return this},i;function c(E){n[E]&&(i[E]=function(x){return new Promise(function(I,k){o.push([E,x,I,k])>1||l(E,x)})})}function l(E,x){try{f(n[E](x))}catch(I){_(o[0][3],I)}}function f(E){E.value instanceof gc?Promise.resolve(E.value.v).then(h,g):_(o[0][2],E)}function h(E){l("next",E)}function g(E){l("throw",E)}function _(E,x){E(x),o.shift(),o.length&&l(o[0][0],o[0][1])}}function jx(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,o){e[i]=t[i]?function(c){return(r=!r)?{value:gc(t[i](c)),done:i==="return"}:o?o(c):c}:o}}function kx(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof Xf=="function"?Xf(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(o){r[o]=t[o]&&function(c){return new Promise(function(l,f){c=t[o](c),i(l,f,c.done,c.value)})}}function i(o,c,l,f){Promise.resolve(f).then(function(h){o({value:h,done:l})},c)}}function qx(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function zx(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function Hx(t){return t&&t.__esModule?t:{default:t}}function Kx(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function Wx(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var Vx=Object.freeze({__proto__:null,__extends:Cx,get __assign(){return Zf},__rest:Ox,__decorate:Mx,__param:Px,__metadata:$x,__awaiter:Tx,__generator:Nx,__createBinding:Rx,__exportStar:Lx,__values:Xf,__read:uv,__spread:Bx,__spreadArrays:Ux,__await:gc,__asyncGenerator:Fx,__asyncDelegator:jx,__asyncValues:kx,__makeTemplateObject:qx,__importStar:zx,__importDefault:Hx,__classPrivateFieldGet:Kx,__classPrivateFieldSet:Wx}),Gx=il(Vx),qi={},hv;function Yx(){if(hv)return qi;hv=1,Object.defineProperty(qi,"__esModule",{value:!0}),qi.isBrowserCryptoAvailable=qi.getSubtleCrypto=qi.getBrowerCrypto=void 0;function t(){return jr?.crypto||jr?.msCrypto||{}}qi.getBrowerCrypto=t;function e(){const n=t();return n.subtle||n.webkitSubtle}qi.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return qi.isBrowserCryptoAvailable=r,qi}var zi={},fv;function Qx(){if(fv)return zi;fv=1,Object.defineProperty(zi,"__esModule",{value:!0}),zi.isBrowser=zi.isNode=zi.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}zi.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}zi.isNode=e;function r(){return!t()&&!e()}return zi.isBrowser=r,zi}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Gx;e.__exportStar(Yx(),t),e.__exportStar(Qx(),t)})(lv);function us(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Ys(t=6){return BigInt(us(t))}function ta(t,e,r){return{id:r||us(),jsonrpc:"2.0",method:t,params:e}}function Wl(t,e){return{id:t,jsonrpc:"2.0",result:e}}function Vl(t,e,r){return{id:t,jsonrpc:"2.0",error:Jx(e,r)}}function Jx(t,e){return typeof t>"u"?av(sv):(typeof t=="string"&&(t=Object.assign(Object.assign({},av(Qf)),{message:t})),typeof e<"u"&&(t.data=e),Ix(t.code)&&(t=Dx(t.code)),t)}class Zx{}class Xx extends Zx{constructor(){super()}}class e9 extends Xx{constructor(e){super()}}const t9="^https?:",r9="^wss?:";function n9(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function dv(t,e){const r=n9(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function pv(t){return dv(t,t9)}function gv(t){return dv(t,r9)}function i9(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function mv(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function e0(t){return mv(t)&&"method"in t}function Gl(t){return mv(t)&&(_i(t)||Mn(t))}function _i(t){return"result"in t}function Mn(t){return"error"in t}class Hi extends e9{constructor(e){super(e),this.events=new Dr.exports.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(ta(e.method,e.params||[],e.id||Ys().toString()),r)}async requestStrict(e,r){return new Promise(async(n,i)=>{if(!this.connection.connected)try{await this.open()}catch(o){i(o)}this.events.on(`${e.id}`,o=>{Mn(o)?i(o.error):n(o.result)});try{await this.connection.send(e,r)}catch(o){i(o)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),Gl(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}}const s9=()=>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"),o9=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",vv=t=>t.split("?")[0],wv=10,a9=s9();class c9{constructor(e){if(this.url=e,this.events=new Dr.exports.EventEmitter,this.registering=!1,!gv(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=n=>{this.onClose(n),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(ki(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!gv(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",o=>{this.resetMaxListeners(),i(o)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return i(new Error("WebSocket connection is missing or invalid"));n(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,n)=>{const i=new URLSearchParams(e).get("origin"),o=lv.isReactNative()?{headers:{origin:i}}:{rejectUnauthorized:!i9(e)},c=new a9(e,[],o);o9()?c.onerror=l=>{const f=l;n(this.emitError(f.error))}:c.on("error",l=>{n(this.emitError(l))}),c.onopen=()=>{this.onOpen(c),r(c)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?lc(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),o=Vl(e,i);this.events.emit("payload",o)}parseError(e,r=this.url){return cv(e,vv(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>wv&&this.events.setMaxListeners(wv)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${vv(this.url)}`));return this.events.emit("register_error",r),r}}var t0={exports:{}};(function(t,e){var r=200,n="__lodash_hash_undefined__",i=1,o=2,c=9007199254740991,l="[object Arguments]",f="[object Array]",h="[object AsyncFunction]",g="[object Boolean]",_="[object Date]",E="[object Error]",x="[object Function]",I="[object GeneratorFunction]",k="[object Map]",W="[object Number]",Y="[object Null]",B="[object Object]",z="[object Promise]",M="[object Proxy]",U="[object RegExp]",F="[object Set]",m="[object String]",$="[object Symbol]",te="[object Undefined]",ee="[object WeakMap]",ne="[object ArrayBuffer]",de="[object DataView]",d="[object Float32Array]",p="[object Float64Array]",b="[object Int8Array]",D="[object Int16Array]",O="[object Int32Array]",T="[object Uint8Array]",L="[object Uint8ClampedArray]",C="[object Uint16Array]",v="[object Uint32Array]",N=/[\\^$.*+?()[\]{}|]/g,oe=/^\[object .+?Constructor\]$/,pe=/^(?:0|[1-9]\d*)$/,A={};A[d]=A[p]=A[b]=A[D]=A[O]=A[T]=A[L]=A[C]=A[v]=!0,A[l]=A[f]=A[ne]=A[g]=A[de]=A[_]=A[E]=A[x]=A[k]=A[W]=A[B]=A[U]=A[F]=A[m]=A[ee]=!1;var re=typeof jr=="object"&&jr&&jr.Object===Object&&jr,q=typeof self=="object"&&self&&self.Object===Object&&self,H=re||q||Function("return this")(),V=e&&!e.nodeType&&e,w=V&&!0&&t&&!t.nodeType&&t,j=w&&w.exports===V,ie=j&&re.process,he=function(){try{return ie&&ie.binding&&ie.binding("util")}catch{}}(),le=he&&he.isTypedArray;function Oe(K,J){for(var fe=-1,Se=K==null?0:K.length,Vt=0,ot=[];++fe<Se;){var Zt=K[fe];J(Zt,fe,K)&&(ot[Vt++]=Zt)}return ot}function Pe(K,J){for(var fe=-1,Se=J.length,Vt=K.length;++fe<Se;)K[Vt+fe]=J[fe];return K}function Ie(K,J){for(var fe=-1,Se=K==null?0:K.length;++fe<Se;)if(J(K[fe],fe,K))return!0;return!1}function Mt(K,J){for(var fe=-1,Se=Array(K);++fe<K;)Se[fe]=J(fe);return Se}function ze(K){return function(J){return K(J)}}function Ce(K,J){return K.has(J)}function Fe(K,J){return K?.[J]}function Ee(K){var J=-1,fe=Array(K.size);return K.forEach(function(Se,Vt){fe[++J]=[Vt,Se]}),fe}function Ae(K,J){return function(fe){return K(J(fe))}}function Ge(K){var J=-1,fe=Array(K.size);return K.forEach(function(Se){fe[++J]=Se}),fe}var be=Array.prototype,xe=Function.prototype,Be=Object.prototype,_e=H["__core-js_shared__"],Me=xe.toString,je=Be.hasOwnProperty,$e=function(){var K=/[^.]+$/.exec(_e&&_e.keys&&_e.keys.IE_PROTO||"");return K?"Symbol(src)_1."+K:""}(),Te=Be.toString,lt=RegExp("^"+Me.call(je).replace(N,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Re=j?H.Buffer:void 0,Ne=H.Symbol,nr=H.Uint8Array,dt=Be.propertyIsEnumerable,Et=be.splice,ir=Ne?Ne.toStringTag:void 0,St=Object.getOwnPropertySymbols,Ot=Re?Re.isBuffer:void 0,Vr=Ae(Object.keys,Object),Ye=bn(H,"DataView"),He=bn(H,"Map"),Rt=bn(H,"Promise"),Qe=bn(H,"Set"),Ve=bn(H,"WeakMap"),Pt=bn(Object,"create"),Xe=Yi(Ye),et=Yi(He),Lt=Yi(Rt),tt=Yi(Qe),Je=Yi(Ve),Ft=Ne?Ne.prototype:void 0,Ze=Ft?Ft.valueOf:void 0;function ke(K){var J=-1,fe=K==null?0:K.length;for(this.clear();++J<fe;){var Se=K[J];this.set(Se[0],Se[1])}}function Ht(){this.__data__=Pt?Pt(null):{},this.size=0}function rt(K){var J=this.has(K)&&delete this.__data__[K];return this.size-=J?1:0,J}function jt(K){var J=this.__data__;if(Pt){var fe=J[K];return fe===n?void 0:fe}return je.call(J,K)?J[K]:void 0}function ti(K){var J=this.__data__;return Pt?J[K]!==void 0:je.call(J,K)}function kt(K,J){var fe=this.__data__;return this.size+=this.has(K)?0:1,fe[K]=Pt&&J===void 0?n:J,this}ke.prototype.clear=Ht,ke.prototype.delete=rt,ke.prototype.get=jt,ke.prototype.has=ti,ke.prototype.set=kt;function vt(K){var J=-1,fe=K==null?0:K.length;for(this.clear();++J<fe;){var Se=K[J];this.set(Se[0],Se[1])}}function Nn(){this.__data__=[],this.size=0}function Rn(K){var J=this.__data__,fe=bo(J,K);if(fe<0)return!1;var Se=J.length-1;return fe==Se?J.pop():Et.call(J,fe,1),--this.size,!0}function Ln(K){var J=this.__data__,fe=bo(J,K);return fe<0?void 0:J[fe][1]}function Bn(K){return bo(this.__data__,K)>-1}function Un(K,J){var fe=this.__data__,Se=bo(fe,K);return Se<0?(++this.size,fe.push([K,J])):fe[Se][1]=J,this}vt.prototype.clear=Nn,vt.prototype.delete=Rn,vt.prototype.get=Ln,vt.prototype.has=Bn,vt.prototype.set=Un;function xr(K){var J=-1,fe=K==null?0:K.length;for(this.clear();++J<fe;){var Se=K[J];this.set(Se[0],Se[1])}}function Ci(){this.size=0,this.__data__={hash:new ke,map:new(He||vt),string:new ke}}function fo(K){var J=Cs(this,K).delete(K);return this.size-=J?1:0,J}function Oi(K){return Cs(this,K).get(K)}function po(K){return Cs(this,K).has(K)}function go(K,J){var fe=Cs(this,K),Se=fe.size;return fe.set(K,J),this.size+=fe.size==Se?0:1,this}xr.prototype.clear=Ci,xr.prototype.delete=fo,xr.prototype.get=Oi,xr.prototype.has=po,xr.prototype.set=go;function Mi(K){var J=-1,fe=K==null?0:K.length;for(this.__data__=new xr;++J<fe;)this.add(K[J])}function Is(K){return this.__data__.set(K,n),this}function Ds(K){return this.__data__.has(K)}Mi.prototype.add=Mi.prototype.push=Is,Mi.prototype.has=Ds;function Gr(K){var J=this.__data__=new vt(K);this.size=J.size}function mo(){this.__data__=new vt,this.size=0}function vo(K){var J=this.__data__,fe=J.delete(K);return this.size=J.size,fe}function wo(K){return this.__data__.get(K)}function yo(K){return this.__data__.has(K)}function Pu(K,J){var fe=this.__data__;if(fe instanceof vt){var Se=fe.__data__;if(!He||Se.length<r-1)return Se.push([K,J]),this.size=++fe.size,this;fe=this.__data__=new xr(Se)}return fe.set(K,J),this.size=fe.size,this}Gr.prototype.clear=mo,Gr.prototype.delete=vo,Gr.prototype.get=wo,Gr.prototype.has=yo,Gr.prototype.set=Pu;function $u(K,J){var fe=Sa(K),Se=!fe&&Hu(K),Vt=!fe&&!Se&&kc(K),ot=!fe&&!Se&&!Vt&&Vu(K),Zt=fe||Se||Vt||ot,gr=Zt?Mt(K.length,String):[],It=gr.length;for(var Gt in K)(J||je.call(K,Gt))&&!(Zt&&(Gt=="length"||Vt&&(Gt=="offset"||Gt=="parent")||ot&&(Gt=="buffer"||Gt=="byteLength"||Gt=="byteOffset")||Fu(Gt,It)))&&gr.push(Gt);return gr}function bo(K,J){for(var fe=K.length;fe--;)if(zu(K[fe][0],J))return fe;return-1}function Fc(K,J,fe){var Se=J(K);return Sa(K)?Se:Pe(Se,fe(K))}function _o(K){return K==null?K===void 0?te:Y:ir&&ir in Object(K)?Bu(K):Td(K)}function jc(K){return Ao(K)&&_o(K)==l}function Eo(K,J,fe,Se,Vt){return K===J?!0:K==null||J==null||!Ao(K)&&!Ao(J)?K!==K&&J!==J:Tu(K,J,fe,Se,Eo,Vt)}function Tu(K,J,fe,Se,Vt,ot){var Zt=Sa(K),gr=Sa(J),It=Zt?f:Pi(K),Gt=gr?f:Pi(J);It=It==l?B:It,Gt=Gt==l?B:Gt;var fr=It==B,ln=Gt==B,mr=It==Gt;if(mr&&kc(K)){if(!kc(J))return!1;Zt=!0,fr=!1}if(mr&&!fr)return ot||(ot=new Gr),Zt||Vu(K)?Aa(K,J,fe,Se,Vt,ot):$d(K,J,It,fe,Se,Vt,ot);if(!(fe&i)){var Xt=fr&&je.call(K,"__wrapped__"),Yr=ln&&je.call(J,"__wrapped__");if(Xt||Yr){var ri=Xt?K.value():K,Fn=Yr?J.value():J;return ot||(ot=new Gr),Vt(ri,Fn,fe,Se,ot)}}return mr?(ot||(ot=new Gr),Lu(K,J,fe,Se,Vt,ot)):!1}function Pd(K){if(!Wu(K)||ku(K))return!1;var J=Ia(K)?lt:oe;return J.test(Yi(K))}function Nu(K){return Ao(K)&&Ku(K.length)&&!!A[_o(K)]}function Ru(K){if(!qu(K))return Vr(K);var J=[];for(var fe in Object(K))je.call(K,fe)&&fe!="constructor"&&J.push(fe);return J}function Aa(K,J,fe,Se,Vt,ot){var Zt=fe&i,gr=K.length,It=J.length;if(gr!=It&&!(Zt&&It>gr))return!1;var Gt=ot.get(K);if(Gt&&ot.get(J))return Gt==J;var fr=-1,ln=!0,mr=fe&o?new Mi:void 0;for(ot.set(K,J),ot.set(J,K);++fr<gr;){var Xt=K[fr],Yr=J[fr];if(Se)var ri=Zt?Se(Yr,Xt,fr,J,K,ot):Se(Xt,Yr,fr,K,J,ot);if(ri!==void 0){if(ri)continue;ln=!1;break}if(mr){if(!Ie(J,function(Fn,$i){if(!Ce(mr,$i)&&(Xt===Fn||Vt(Xt,Fn,fe,Se,ot)))return mr.push($i)})){ln=!1;break}}else if(!(Xt===Yr||Vt(Xt,Yr,fe,Se,ot))){ln=!1;break}}return ot.delete(K),ot.delete(J),ln}function $d(K,J,fe,Se,Vt,ot,Zt){switch(fe){case de:if(K.byteLength!=J.byteLength||K.byteOffset!=J.byteOffset)return!1;K=K.buffer,J=J.buffer;case ne:return!(K.byteLength!=J.byteLength||!ot(new nr(K),new nr(J)));case g:case _:case W:return zu(+K,+J);case E:return K.name==J.name&&K.message==J.message;case U:case m:return K==J+"";case k:var gr=Ee;case F:var It=Se&i;if(gr||(gr=Ge),K.size!=J.size&&!It)return!1;var Gt=Zt.get(K);if(Gt)return Gt==J;Se|=o,Zt.set(K,J);var fr=Aa(gr(K),gr(J),Se,Vt,ot,Zt);return Zt.delete(K),fr;case $:if(Ze)return Ze.call(K)==Ze.call(J)}return!1}function Lu(K,J,fe,Se,Vt,ot){var Zt=fe&i,gr=xa(K),It=gr.length,Gt=xa(J),fr=Gt.length;if(It!=fr&&!Zt)return!1;for(var ln=It;ln--;){var mr=gr[ln];if(!(Zt?mr in J:je.call(J,mr)))return!1}var Xt=ot.get(K);if(Xt&&ot.get(J))return Xt==J;var Yr=!0;ot.set(K,J),ot.set(J,K);for(var ri=Zt;++ln<It;){mr=gr[ln];var Fn=K[mr],$i=J[mr];if(Se)var qc=Zt?Se($i,Fn,mr,J,K,ot):Se(Fn,$i,mr,K,J,ot);if(!(qc===void 0?Fn===$i||Vt(Fn,$i,fe,Se,ot):qc)){Yr=!1;break}ri||(ri=mr=="constructor")}if(Yr&&!ri){var xo=K.constructor,Sr=J.constructor;xo!=Sr&&"constructor"in K&&"constructor"in J&&!(typeof xo=="function"&&xo instanceof xo&&typeof Sr=="function"&&Sr instanceof Sr)&&(Yr=!1)}return ot.delete(K),ot.delete(J),Yr}function xa(K){return Fc(K,Ld,Uu)}function Cs(K,J){var fe=K.__data__;return ju(J)?fe[typeof J=="string"?"string":"hash"]:fe.map}function bn(K,J){var fe=Fe(K,J);return Pd(fe)?fe:void 0}function Bu(K){var J=je.call(K,ir),fe=K[ir];try{K[ir]=void 0;var Se=!0}catch{}var Vt=Te.call(K);return Se&&(J?K[ir]=fe:delete K[ir]),Vt}var Uu=St?function(K){return K==null?[]:(K=Object(K),Oe(St(K),function(J){return dt.call(K,J)}))}:Wt,Pi=_o;(Ye&&Pi(new Ye(new ArrayBuffer(1)))!=de||He&&Pi(new He)!=k||Rt&&Pi(Rt.resolve())!=z||Qe&&Pi(new Qe)!=F||Ve&&Pi(new Ve)!=ee)&&(Pi=function(K){var J=_o(K),fe=J==B?K.constructor:void 0,Se=fe?Yi(fe):"";if(Se)switch(Se){case Xe:return de;case et:return k;case Lt:return z;case tt:return F;case Je:return ee}return J});function Fu(K,J){return J=J??c,!!J&&(typeof K=="number"||pe.test(K))&&K>-1&&K%1==0&&K<J}function ju(K){var J=typeof K;return J=="string"||J=="number"||J=="symbol"||J=="boolean"?K!=="__proto__":K===null}function ku(K){return!!$e&&$e in K}function qu(K){var J=K&&K.constructor,fe=typeof J=="function"&&J.prototype||Be;return K===fe}function Td(K){return Te.call(K)}function Yi(K){if(K!=null){try{return Me.call(K)}catch{}try{return K+""}catch{}}return""}function zu(K,J){return K===J||K!==K&&J!==J}var Hu=jc(function(){return arguments}())?jc:function(K){return Ao(K)&&je.call(K,"callee")&&!dt.call(K,"callee")},Sa=Array.isArray;function Nd(K){return K!=null&&Ku(K.length)&&!Ia(K)}var kc=Ot||Kt;function Rd(K,J){return Eo(K,J)}function Ia(K){if(!Wu(K))return!1;var J=_o(K);return J==x||J==I||J==h||J==M}function Ku(K){return typeof K=="number"&&K>-1&&K%1==0&&K<=c}function Wu(K){var J=typeof K;return K!=null&&(J=="object"||J=="function")}function Ao(K){return K!=null&&typeof K=="object"}var Vu=le?ze(le):Nu;function Ld(K){return Nd(K)?$u(K):Ru(K)}function Wt(){return[]}function Kt(){return!1}t.exports=Rd})(t0,t0.exports);var l9=t0.exports;function u9(t,e){return e=e||{},new Promise(function(r,n){var i=new XMLHttpRequest,o=[],c=[],l={},f=function(){return{ok:(i.status/100|0)==2,statusText:i.statusText,status:i.status,url:i.responseURL,text:function(){return Promise.resolve(i.responseText)},json:function(){return Promise.resolve(i.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([i.response]))},clone:f,headers:{keys:function(){return o},entries:function(){return c},get:function(g){return l[g.toLowerCase()]},has:function(g){return g.toLowerCase()in l}}}};for(var h in i.open(e.method||"get",t,!0),i.onload=function(){i.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(g,_,E){o.push(_=_.toLowerCase()),c.push([_,E]),l[_]=l[_]?l[_]+","+E:E}),r(f())},i.onerror=n,i.withCredentials=e.credentials=="include",e.headers)i.setRequestHeader(h,e.headers[h]);i.send(e.body||null)})}var h9=Object.freeze({__proto__:null,default:u9}),yv=il(h9),f9=self.fetch||(self.fetch=yv.default||yv),d9=Object.defineProperty,bv=Object.getOwnPropertySymbols,p9=Object.prototype.hasOwnProperty,g9=Object.prototype.propertyIsEnumerable,_v=(t,e,r)=>e in t?d9(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Kr=(t,e)=>{for(var r in e||(e={}))p9.call(e,r)&&_v(t,r,e[r]);if(bv)for(var r of bv(e))g9.call(e,r)&&_v(t,r,e[r]);return t};function m9(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var o=t.charAt(i),c=o.charCodeAt(0);if(r[c]!==255)throw new TypeError(o+" is ambiguous");r[c]=i}var l=t.length,f=t.charAt(0),h=Math.log(l)/Math.log(256),g=Math.log(256)/Math.log(l);function _(I){if(I instanceof Uint8Array||(ArrayBuffer.isView(I)?I=new Uint8Array(I.buffer,I.byteOffset,I.byteLength):Array.isArray(I)&&(I=Uint8Array.from(I))),!(I instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(I.length===0)return"";for(var k=0,W=0,Y=0,B=I.length;Y!==B&&I[Y]===0;)Y++,k++;for(var z=(B-Y)*g+1>>>0,M=new Uint8Array(z);Y!==B;){for(var U=I[Y],F=0,m=z-1;(U!==0||F<W)&&m!==-1;m--,F++)U+=256*M[m]>>>0,M[m]=U%l>>>0,U=U/l>>>0;if(U!==0)throw new Error("Non-zero carry");W=F,Y++}for(var $=z-W;$!==z&&M[$]===0;)$++;for(var te=f.repeat(k);$<z;++$)te+=t.charAt(M[$]);return te}function E(I){if(typeof I!="string")throw new TypeError("Expected String");if(I.length===0)return new Uint8Array;var k=0;if(I[k]!==" "){for(var W=0,Y=0;I[k]===f;)W++,k++;for(var B=(I.length-k)*h+1>>>0,z=new Uint8Array(B);I[k];){var M=r[I.charCodeAt(k)];if(M===255)return;for(var U=0,F=B-1;(M!==0||U<Y)&&F!==-1;F--,U++)M+=l*z[F]>>>0,z[F]=M%256>>>0,M=M/256>>>0;if(M!==0)throw new Error("Non-zero carry");Y=U,k++}if(I[k]!==" "){for(var m=B-Y;m!==B&&z[m]===0;)m++;for(var $=new Uint8Array(W+(B-m)),te=W;m!==B;)$[te++]=z[m++];return $}}}function x(I){var k=E(I);if(k)return k;throw new Error(`Non-${e} character`)}return{encode:_,decodeUnsafe:E,decode:x}}var v9=m9,w9=v9;const Ev=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},y9=t=>new TextEncoder().encode(t),b9=t=>new TextDecoder().decode(t);class _9{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class E9{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Av(this,e)}}class A9{constructor(e){this.decoders=e}or(e){return Av(this,e)}decode(e){const r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Av=(t,e)=>new A9(Kr(Kr({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class x9{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new _9(e,r,n),this.decoder=new E9(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Yl=({name:t,prefix:e,encode:r,decode:n})=>new x9(t,e,r,n),mc=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=w9(r,e);return Yl({prefix:t,name:e,encode:n,decode:o=>Ev(i(o))})},S9=(t,e,r,n)=>{const i={};for(let g=0;g<e.length;++g)i[e[g]]=g;let o=t.length;for(;t[o-1]==="=";)--o;const c=new Uint8Array(o*r/8|0);let l=0,f=0,h=0;for(let g=0;g<o;++g){const _=i[t[g]];if(_===void 0)throw new SyntaxError(`Non-${n} character`);f=f<<r|_,l+=r,l>=8&&(l-=8,c[h++]=255&f>>l)}if(l>=r||255&f<<8-l)throw new SyntaxError("Unexpected end of data");return c},I9=(t,e,r)=>{const n=e[e.length-1]==="=",i=(1<<r)-1;let o="",c=0,l=0;for(let f=0;f<t.length;++f)for(l=l<<8|t[f],c+=8;c>r;)c-=r,o+=e[i&l>>c];if(c&&(o+=e[i&l<<r-c]),n)for(;o.length*r&7;)o+="=";return o},$r=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>Yl({prefix:e,name:t,encode(i){return I9(i,n,r)},decode(i){return S9(i,n,r,t)}}),D9=Yl({prefix:"\0",name:"identity",encode:t=>b9(t),decode:t=>y9(t)});var C9=Object.freeze({__proto__:null,identity:D9});const O9=$r({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var M9=Object.freeze({__proto__:null,base2:O9});const P9=$r({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var $9=Object.freeze({__proto__:null,base8:P9});const T9=mc({prefix:"9",name:"base10",alphabet:"0123456789"});var N9=Object.freeze({__proto__:null,base10:T9});const R9=$r({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),L9=$r({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var B9=Object.freeze({__proto__:null,base16:R9,base16upper:L9});const U9=$r({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),F9=$r({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),j9=$r({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),k9=$r({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),q9=$r({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),z9=$r({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),H9=$r({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),K9=$r({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),W9=$r({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var V9=Object.freeze({__proto__:null,base32:U9,base32upper:F9,base32pad:j9,base32padupper:k9,base32hex:q9,base32hexupper:z9,base32hexpad:H9,base32hexpadupper:K9,base32z:W9});const G9=mc({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Y9=mc({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Q9=Object.freeze({__proto__:null,base36:G9,base36upper:Y9});const J9=mc({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Z9=mc({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var X9=Object.freeze({__proto__:null,base58btc:J9,base58flickr:Z9});const eS=$r({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),tS=$r({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),rS=$r({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),nS=$r({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var iS=Object.freeze({__proto__:null,base64:eS,base64pad:tS,base64url:rS,base64urlpad:nS});const xv=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),sS=xv.reduce((t,e,r)=>(t[r]=e,t),[]),oS=xv.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function aS(t){return t.reduce((e,r)=>(e+=sS[r],e),"")}function cS(t){const e=[];for(const r of t){const n=oS[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const lS=Yl({prefix:"\u{1F680}",name:"base256emoji",encode:aS,decode:cS});var uS=Object.freeze({__proto__:null,base256emoji:lS}),hS=Iv,Sv=128,fS=127,dS=~fS,pS=Math.pow(2,31);function Iv(t,e,r){e=e||[],r=r||0;for(var n=r;t>=pS;)e[r++]=t&255|Sv,t/=128;for(;t&dS;)e[r++]=t&255|Sv,t>>>=7;return e[r]=t|0,Iv.bytes=r-n+1,e}var gS=r0,mS=128,Dv=127;function r0(t,n){var r=0,n=n||0,i=0,o=n,c,l=t.length;do{if(o>=l)throw r0.bytes=0,new RangeError("Could not decode varint");c=t[o++],r+=i<28?(c&Dv)<<i:(c&Dv)*Math.pow(2,i),i+=7}while(c>=mS);return r0.bytes=o-n,r}var vS=Math.pow(2,7),wS=Math.pow(2,14),yS=Math.pow(2,21),bS=Math.pow(2,28),_S=Math.pow(2,35),ES=Math.pow(2,42),AS=Math.pow(2,49),xS=Math.pow(2,56),SS=Math.pow(2,63),IS=function(t){return t<vS?1:t<wS?2:t<yS?3:t<bS?4:t<_S?5:t<ES?6:t<AS?7:t<xS?8:t<SS?9:10},DS={encode:hS,decode:gS,encodingLength:IS},Cv=DS;const Ov=(t,e,r=0)=>(Cv.encode(t,e,r),e),Mv=t=>Cv.encodingLength(t),n0=(t,e)=>{const r=e.byteLength,n=Mv(t),i=n+Mv(r),o=new Uint8Array(i+r);return Ov(t,o,0),Ov(r,o,n),o.set(e,i),new CS(t,r,e,o)};class CS{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const Pv=({name:t,code:e,encode:r})=>new OS(t,e,r);class OS{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?n0(this.code,r):r.then(n=>n0(this.code,n))}else throw Error("Unknown type, must be binary type")}}const $v=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),MS=Pv({name:"sha2-256",code:18,encode:$v("SHA-256")}),PS=Pv({name:"sha2-512",code:19,encode:$v("SHA-512")});var $S=Object.freeze({__proto__:null,sha256:MS,sha512:PS});const Tv=0,TS="identity",Nv=Ev;var NS=Object.freeze({__proto__:null,identity:{code:Tv,name:TS,encode:Nv,digest:t=>n0(Tv,Nv(t))}});new TextEncoder,new TextDecoder;const Rv=Kr(Kr(Kr(Kr(Kr(Kr(Kr(Kr(Kr(Kr({},C9),M9),$9),N9),B9),V9),Q9),X9),iS),uS);Kr(Kr({},$S),NS);function RS(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function Lv(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const Bv=Lv("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),i0=Lv("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=RS(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),LS=Kr({utf8:Bv,"utf-8":Bv,hex:Rv.base16,latin1:i0,ascii:i0,binary:i0},Rv);function BS(t,e="utf8"){const r=LS[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t,"utf8"):r.decoder.decode(`${r.prefix}${t}`)}const Uv="wc",US=2,s0="core",hs=`${Uv}@2:${s0}:`,FS={name:s0,logger:"error"},jS={database:":memory:"},kS="crypto",Fv="client_ed25519_seed",qS=ye.ONE_DAY,zS="keychain",HS="0.3",KS="messages",WS="0.3",VS=ye.SIX_HOURS,GS="publisher",jv="irn",YS="error",kv="wss://relay.walletconnect.com",qv="wss://relay.walletconnect.org",QS="relayer",on={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},JS="_subscription",Pn={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},ZS=ye.ONE_SECOND,XS="2.13.2",eI=1e4,tI="0.3",rI="WALLETCONNECT_CLIENT_ID",Ei={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},nI="subscription",iI="0.3",sI=ye.FIVE_SECONDS*1e3,oI="pairing",aI="0.3",vc={wc_pairingDelete:{req:{ttl:ye.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:ye.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:ye.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:ye.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:ye.ONE_DAY,prompt:!1,tag:0},res:{ttl:ye.ONE_DAY,prompt:!1,tag:0}}},ra={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},ei={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},cI="history",lI="0.3",uI="expirer",$n={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},hI="0.3",o0="verify-api",na="https://verify.walletconnect.com",a0="https://verify.walletconnect.org",fI=[na,a0],dI="echo",pI="https://echo.walletconnect.com";class gI{constructor(e,r){this.core=e,this.logger=r,this.keychain=new Map,this.name=zS,this.version=HS,this.initialized=!1,this.storagePrefix=hs,this.init=async()=>{if(!this.initialized){const n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}},this.has=n=>(this.isInitialized(),this.keychain.has(n)),this.set=async(n,i)=>{this.isInitialized(),this.keychain.set(n,i),await this.persist()},this.get=n=>{this.isInitialized();const i=this.keychain.get(n);if(typeof i>"u"){const{message:o}=me("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(o)}return i},this.del=async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()},this.core=e,this.logger=sn(r,this.name)}get context(){return nn(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,eg(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?tg(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=me("NOT_INITIALIZED",this.name);throw new Error(e)}}}class mI{constructor(e,r,n){this.core=e,this.logger=r,this.name=kS,this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=i=>(this.isInitialized(),this.keychain.has(i)),this.getClientId=async()=>{this.isInitialized();const i=await this.getClientSeed(),o=rv(i);return tv(o.publicKey)},this.generateKeyPair=()=>{this.isInitialized();const i=FE();return this.setPrivateKey(i.publicKey,i.privateKey)},this.signJWT=async i=>{this.isInitialized();const o=await this.getClientSeed(),c=rv(o),l=Pf();return await vx(l,i,qS,c)},this.generateSharedKey=(i,o,c)=>{this.isInitialized();const l=this.getPrivateKey(i),f=jE(l,o);return this.setSymKey(f,c)},this.setSymKey=async(i,o)=>{this.isInitialized();const c=o||Tl(i);return await this.keychain.set(c,i),c},this.deleteKeyPair=async i=>{this.isInitialized(),await this.keychain.del(i)},this.deleteSymKey=async i=>{this.isInitialized(),await this.keychain.del(i)},this.encode=async(i,o,c)=>{this.isInitialized();const l=ym(c),f=ki(o);if(bm(l)){const E=l.senderPublicKey,x=l.receiverPublicKey;i=await this.generateSharedKey(E,x)}const h=this.getSymKey(i),{type:g,senderPublicKey:_}=l;return qE({type:g,symKey:h,message:f,senderPublicKey:_})},this.decode=async(i,o,c)=>{this.isInitialized();const l=KE(o,c);if(bm(l)){const f=l.receiverPublicKey,h=l.senderPublicKey;i=await this.generateSharedKey(f,h)}try{const f=this.getSymKey(i),h=zE({symKey:f,encoded:o});return lc(h)}catch(f){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(f)}},this.getPayloadType=i=>{const o=Nl(i);return nc(o.type)},this.getPayloadSenderPublicKey=i=>{const o=Nl(i);return o.senderPublicKey?bx(o.senderPublicKey,zr):void 0},this.core=e,this.logger=sn(r,this.name),this.keychain=n||new gI(this.core,this.logger)}get context(){return nn(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(Fv)}catch{e=Pf(),await this.keychain.set(Fv,e)}return BS(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=me("NOT_INITIALIZED",this.name);throw new Error(e)}}}class vI extends V7{constructor(e,r){super(e,r),this.logger=e,this.core=r,this.messages=new Map,this.name=KS,this.version=WS,this.initialized=!1,this.storagePrefix=hs,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}},this.set=async(n,i)=>{this.isInitialized();const o=Ws(i);let c=this.messages.get(n);return typeof c>"u"&&(c={}),typeof c[o]<"u"||(c[o]=i,this.messages.set(n,c),await this.persist()),o},this.get=n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i},this.has=(n,i)=>{this.isInitialized();const o=this.get(n),c=Ws(i);return typeof o[c]<"u"},this.del=async n=>{this.isInitialized(),this.messages.delete(n),await this.persist()},this.logger=sn(e,this.name),this.core=r}get context(){return nn(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,eg(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?tg(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=me("NOT_INITIALIZED",this.name);throw new Error(e)}}}class wI extends G7{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.events=new Dr.exports.EventEmitter,this.name=GS,this.queue=new Map,this.publishTimeout=ye.toMiliseconds(ye.ONE_MINUTE),this.failedPublishTimeout=ye.toMiliseconds(ye.ONE_SECOND),this.needsTransportRestart=!1,this.publish=async(n,i,o)=>{var c;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:o}});const l=o?.ttl||VS,f=$f(o),h=o?.prompt||!1,g=o?.tag||0,_=o?.id||Ys().toString(),E={topic:n,message:i,opts:{ttl:l,relay:f,prompt:h,tag:g,id:_}},x=`Failed to publish payload, please try again. id:${_} tag:${g}`,I=Date.now();let k,W=1;try{for(;k===void 0;){if(Date.now()-I>this.publishTimeout)throw new Error(x);this.logger.trace({id:_,attempts:W},`publisher.publish - attempt ${W}`),k=await await jo(this.rpcPublish(n,i,l,f,h,g,_).catch(Y=>this.logger.warn(Y)),this.publishTimeout,x),W++,k||await new Promise(Y=>setTimeout(Y,this.failedPublishTimeout))}this.relayer.events.emit(on.publish,E),this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{id:_,topic:n,message:i,opts:o}})}catch(Y){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(Y),(c=o?.internal)!=null&&c.throwOnFailedPublish)throw Y;this.queue.set(_,E)}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.relayer=e,this.logger=sn(r,this.name),this.registerEventListeners()}get context(){return nn(this.logger)}rpcPublish(e,r,n,i,o,c,l){var f,h,g,_;const E={method:ic(i.protocol).publish,params:{topic:e,message:r,ttl:n,prompt:o,tag:c},id:l};return Hr((f=E.params)==null?void 0:f.prompt)&&((h=E.params)==null||delete h.prompt),Hr((g=E.params)==null?void 0:g.tag)&&((_=E.params)==null||delete _.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:E}),this.relayer.request(E)}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async e=>{const{topic:r,message:n,opts:i}=e;await this.publish(r,n,i)})}registerEventListeners(){this.relayer.core.heartbeat.on(uc.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(on.connection_stalled);return}this.checkQueue()}),this.relayer.on(on.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}class yI{constructor(){this.map=new Map,this.set=(e,r)=>{const n=this.get(e);this.exists(e,r)||this.map.set(e,[...n,r])},this.get=e=>this.map.get(e)||[],this.exists=(e,r)=>this.get(e).includes(r),this.delete=(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const n=this.get(e);if(!this.exists(e,r))return;const i=n.filter(o=>o!==r);if(!i.length){this.map.delete(e);return}this.map.set(e,i)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}}var bI=Object.defineProperty,_I=Object.defineProperties,EI=Object.getOwnPropertyDescriptors,zv=Object.getOwnPropertySymbols,AI=Object.prototype.hasOwnProperty,xI=Object.prototype.propertyIsEnumerable,Hv=(t,e,r)=>e in t?bI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,wc=(t,e)=>{for(var r in e||(e={}))AI.call(e,r)&&Hv(t,r,e[r]);if(zv)for(var r of zv(e))xI.call(e,r)&&Hv(t,r,e[r]);return t},c0=(t,e)=>_I(t,EI(e));class SI extends J7{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.subscriptions=new Map,this.topicMap=new yI,this.events=new Dr.exports.EventEmitter,this.name=nI,this.version=iI,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=hs,this.subscribeTimeout=ye.toMiliseconds(ye.ONE_MINUTE),this.restartInProgress=!1,this.batchSubscribeTopicsLimit=500,this.pendingBatchMessages=[],this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),this.clientId=await this.relayer.core.crypto.getClientId())},this.subscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}});try{const o=$f(i),c={topic:n,relay:o};this.pending.set(n,c);const l=await this.rpcSubscribe(n,o);return typeof l=="string"&&(this.onSubscribe(l,c),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}})),l}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}},this.unsubscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(n,i.id,i):await this.unsubscribeByTopic(n,i)},this.isSubscribed=async n=>{if(this.topics.includes(n))return!0;const i=`${this.pendingSubscriptionWatchLabel}_${n}`;return await new Promise((o,c)=>{const l=new ye.Watch;l.start(i);const f=setInterval(()=>{!this.pending.has(n)&&this.topics.includes(n)&&(clearInterval(f),l.stop(i),o(!0)),l.elapsed(i)>=sI&&(clearInterval(f),l.stop(i),c(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1)},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.start=async()=>{await this.onConnect()},this.stop=async()=>{await this.onDisconnect()},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=sn(r,this.name),this.clientId=""}get context(){return nn(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}hasSubscription(e,r){let n=!1;try{n=this.getSubscription(e).topic===r}catch{}return n}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){const n=this.topicMap.get(e);await Promise.all(n.map(async i=>await this.unsubscribeById(e,i,r)))}async unsubscribeById(e,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}});try{const i=$f(n);await this.rpcUnsubscribe(e,r,i);const o=Ut("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,o),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,r){const n={method:ic(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{return await await jo(this.relayer.request(n).catch(i=>this.logger.warn(i)),this.subscribeTimeout)?Ws(e+this.clientId):null}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(on.connection_stalled)}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,n={method:ic(r.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{return await await jo(this.relayer.request(n).catch(i=>this.logger.warn(i)),this.subscribeTimeout)}catch{this.relayer.events.emit(on.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,n={method:ic(r.protocol).batchFetchMessages,params:{topics:e.map(o=>o.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});let i;try{i=await await jo(this.relayer.request(n).catch(o=>this.logger.warn(o)),this.subscribeTimeout)}catch{this.relayer.events.emit(on.connection_stalled)}return i}rpcUnsubscribe(e,r,n){const i={method:ic(n.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,r){this.setSubscription(e,c0(wc({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,wc({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,n){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,n),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r)}addSubscription(e,r){this.subscriptions.set(e,wc({},r)),this.topicMap.set(r.topic,e),this.events.emit(Ei.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const r=this.subscriptions.get(e);if(!r){const{message:n}=me("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(Ei.deleted,c0(wc({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Ei.sync)}async reset(){if(this.cached.length){const e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<e;r++){const n=this.cached.splice(0,this.batchSubscribeTopicsLimit);await this.batchFetchMessages(n),await this.batchSubscribe(n)}}this.events.emit(Ei.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:r}=me("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){if(!e.length)return;const r=await this.rpcBatchSubscribe(e);wi(r)&&this.onBatchSubscribe(r.map((n,i)=>c0(wc({},e[i]),{id:n})))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const r=await this.rpcBatchFetchMessages(e);r&&r.messages&&(this.pendingBatchMessages=this.pendingBatchMessages.concat(r.messages))}async onConnect(){await this.restart(),this.onEnable()}onDisconnect(){this.onDisable()}async checkPending(){if(!this.initialized||!this.relayer.connected)return;const e=[];this.pending.forEach(r=>{e.push(r)}),await this.batchSubscribe(e),this.pendingBatchMessages.length&&(await this.relayer.handleBatchMessageEvents(this.pendingBatchMessages),this.pendingBatchMessages=[])}registerEventListeners(){this.relayer.core.heartbeat.on(uc.pulse,async()=>{await this.checkPending()}),this.events.on(Ei.created,async e=>{const r=Ei.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()}),this.events.on(Ei.deleted,async e=>{const r=Ei.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=me("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){this.restartInProgress&&await new Promise(e=>{const r=setInterval(()=>{this.restartInProgress||(clearInterval(r),e())},this.pollingInterval)})}}var II=Object.defineProperty,Kv=Object.getOwnPropertySymbols,DI=Object.prototype.hasOwnProperty,CI=Object.prototype.propertyIsEnumerable,Wv=(t,e,r)=>e in t?II(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,OI=(t,e)=>{for(var r in e||(e={}))DI.call(e,r)&&Wv(t,r,e[r]);if(Kv)for(var r of Kv(e))CI.call(e,r)&&Wv(t,r,e[r]);return t};class MI extends Y7{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new Dr.exports.EventEmitter,this.name=QS,this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.connectionStatusPollingInterval=20,this.staleConnectionErrors=["socket hang up","stalled","interrupted"],this.hasExperiencedNetworkDisruption=!1,this.requestsInFlight=new Map,this.heartBeatTimeout=ye.toMiliseconds(ye.THIRTY_SECONDS+ye.ONE_SECOND),this.request=async r=>{var n,i;this.logger.debug("Publishing Request Payload");const o=r.id||Ys().toString();await this.toEstablishConnection();try{const c=this.provider.request(r);this.requestsInFlight.set(o,{promise:c,request:r}),this.logger.trace({id:o,method:r.method,topic:(n=r.params)==null?void 0:n.topic},"relayer.request - attempt to publish...");const l=await new Promise(async(f,h)=>{const g=()=>{h(new Error(`relayer.request - publish interrupted, id: ${o}`))};this.provider.on(Pn.disconnect,g);const _=await c;this.provider.off(Pn.disconnect,g),f(_)});return this.logger.trace({id:o,method:r.method,topic:(i=r.params)==null?void 0:i.topic},"relayer.request - published"),l}catch(c){throw this.logger.debug(`Failed to Publish Request: ${o}`),c}finally{this.requestsInFlight.delete(o)}},this.resetPingTimeout=()=>{if(Wa())try{clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,n,i;(i=(n=(r=this.provider)==null?void 0:r.connection)==null?void 0:n.socket)==null||i.terminate()},this.heartBeatTimeout)}catch(r){this.logger.warn(r)}},this.onPayloadHandler=r=>{this.onProviderPayload(r),this.resetPingTimeout()},this.onConnectHandler=()=>{this.startPingTimeout(),this.events.emit(on.connect)},this.onDisconnectHandler=()=>{this.onProviderDisconnect()},this.onProviderErrorHandler=r=>{this.logger.error(r),this.events.emit(on.error,r),this.logger.info("Fatal socket error received, closing transport"),this.transportClose()},this.registerProviderListeners=()=>{this.provider.on(Pn.payload,this.onPayloadHandler),this.provider.on(Pn.connect,this.onConnectHandler),this.provider.on(Pn.disconnect,this.onDisconnectHandler),this.provider.on(Pn.error,this.onProviderErrorHandler)},this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?sn(e.logger,this.name):yi(Hl({level:e.logger||YS})),this.messages=new vI(this.logger,e.core),this.subscriber=new SI(this,this.logger),this.publisher=new wI(this,this.logger),this.relayUrl=e?.relayUrl||kv,this.projectId=e.projectId,this.bundleId=C8(),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),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 ${qv}...`),await this.restartTransport(qv)}this.initialized=!0,setTimeout(async()=>{this.subscriber.topics.length===0&&this.subscriber.pending.size===0&&(this.logger.info("No topics subscribed to after init, closing transport"),await this.transportClose(),this.transportExplicitlyClosed=!1)},eI)}get context(){return nn(this.logger)}get connected(){var e,r,n;return((n=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===1}get connecting(){var e,r,n;return((n=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===0}async publish(e,r,n){this.isInitialized(),await this.publisher.publish(e,r,n),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now()})}async subscribe(e,r){var n;this.isInitialized();let i=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",o;const c=l=>{l.topic===e&&(this.subscriber.off(Ei.created,c),o())};return await Promise.all([new Promise(l=>{o=l,this.subscriber.on(Ei.created,c)}),new Promise(async l=>{i=await this.subscriber.subscribe(e,r)||i,l()})]),i}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportDisconnect(){if(!this.hasExperiencedNetworkDisruption&&this.connected&&this.requestsInFlight.size>0)try{await Promise.all(Array.from(this.requestsInFlight.values()).map(e=>e.promise))}catch(e){this.logger.warn(e)}this.hasExperiencedNetworkDisruption||this.connected?await jo(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),await this.createProvider(),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;try{await new Promise(async(r,n)=>{const i=()=>{this.provider.off(Pn.disconnect,i),n(new Error("Connection interrupted while trying to subscribe"))};this.provider.on(Pn.disconnect,i),await jo(this.provider.connect(),ye.toMiliseconds(ye.ONE_MINUTE),`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{n(o)}),await this.subscriber.start(),this.hasExperiencedNetworkDisruption=!1,r()})}catch(r){this.logger.error(r);const n=r;if(this.hasExperiencedNetworkDisruption=!0,!this.isConnectionStalled(n.message))throw r}finally{this.connectionAttemptInProgress=!1}}async restartTransport(e){this.connectionAttemptInProgress||(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await $m())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(e?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const r=e.sort((n,i)=>n.publishedAt-i.publishedAt);this.logger.trace(`Batch of ${r.length} message events sorted`);for(const n of r)try{await this.onMessageEvent(n)}catch(i){this.logger.warn(i)}this.logger.trace(`Batch of ${r.length} message events processed`)}startPingTimeout(){var e,r,n,i,o;if(Wa())try{(r=(e=this.provider)==null?void 0:e.connection)!=null&&r.socket&&((o=(i=(n=this.provider)==null?void 0:n.connection)==null?void 0:i.socket)==null||o.once("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(c){this.logger.warn(c)}}isConnectionStalled(e){return this.staleConnectionErrors.some(r=>e.includes(r))}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Hi(new c9(N8({sdkVersion:XS,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId}))),this.registerProviderListeners()}async recordMessageEvent(e){const{topic:r,message:n}=e;await this.messages.set(r,n)}async shouldIgnoreMessageEvent(e){const{topic:r,message:n}=e;if(!n||n.length===0)return this.logger.debug(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isSubscribed(r))return this.logger.debug(`Ignoring message for non-subscribed topic ${r}`),!0;const i=this.messages.has(r,n);return i&&this.logger.debug(`Ignoring duplicate message: ${n}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),e0(e)){if(!e.method.endsWith(JS))return;const r=e.params,{topic:n,message:i,publishedAt:o}=r.data,c={topic:n,message:i,publishedAt:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(OI({type:"event",event:r.id},c)),this.events.emit(r.id,c),await this.acknowledgePayload(e),await this.onMessageEvent(c)}else Gl(e)&&this.events.emit(on.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(on.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const r=Wl(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(Pn.payload,this.onPayloadHandler),this.provider.off(Pn.connect,this.onConnectHandler),this.provider.off(Pn.disconnect,this.onDisconnectHandler),this.provider.off(Pn.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await $m();RA(async r=>{e!==r&&(e=r,r?await this.restartTransport().catch(n=>this.logger.error(n)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))})}async onProviderDisconnect(){await this.subscriber.stop(),this.requestsInFlight.clear(),clearTimeout(this.pingTimeout),this.events.emit(on.disconnect),this.connectionAttemptInProgress=!1,!this.transportExplicitlyClosed&&setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e))},ye.toMiliseconds(ZS))}isInitialized(){if(!this.initialized){const{message:e}=me("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&(this.connectionAttemptInProgress&&await new Promise(e=>{const r=setInterval(()=>{this.connected&&(clearInterval(r),e())},this.connectionStatusPollingInterval)}),await this.transportOpen())}}var PI=Object.defineProperty,Vv=Object.getOwnPropertySymbols,$I=Object.prototype.hasOwnProperty,TI=Object.prototype.propertyIsEnumerable,Gv=(t,e,r)=>e in t?PI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Yv=(t,e)=>{for(var r in e||(e={}))$I.call(e,r)&&Gv(t,r,e[r]);if(Vv)for(var r of Vv(e))TI.call(e,r)&&Gv(t,r,e[r]);return t};class Qs extends Q7{constructor(e,r,n,i=hs,o=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,this.map=new Map,this.version=tI,this.cached=[],this.initialized=!1,this.storagePrefix=hs,this.recentlyDeleted=[],this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(c=>{this.getKey&&c!==null&&!Hr(c)?this.map.set(this.getKey(c),c):fA(c)?this.map.set(c.id,c):dA(c)&&this.map.set(c.topic,c)}),this.cached=[],this.initialized=!0)},this.set=async(c,l)=>{this.isInitialized(),this.map.has(c)?await this.update(c,l):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:c,value:l}),this.map.set(c,l),await this.persist())},this.get=c=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:c}),this.getData(c)),this.getAll=c=>(this.isInitialized(),c?this.values.filter(l=>Object.keys(c).every(f=>l9(l[f],c[f]))):this.values),this.update=async(c,l)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:c,update:l});const f=Yv(Yv({},this.getData(c)),l);this.map.set(c,f),await this.persist()},this.delete=async(c,l)=>{this.isInitialized(),this.map.has(c)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:c,reason:l}),this.map.delete(c),this.addToRecentlyDeleted(c),await this.persist())},this.logger=sn(r,this.name),this.storagePrefix=i,this.getKey=o}get context(){return nn(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const r=this.map.get(e);if(!r){if(this.recentlyDeleted.includes(e)){const{message:i}=me("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}const{message:n}=me("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:r}=me("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=me("NOT_INITIALIZED",this.name);throw new Error(e)}}}class NI{constructor(e,r){this.core=e,this.logger=r,this.name=oI,this.version=aI,this.events=new Dr.exports,this.initialized=!1,this.storagePrefix=hs,this.ignoredPayloadTypes=[ji],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=({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]},this.create=async n=>{this.isInitialized();const i=Pf(),o=await this.core.crypto.setSymKey(i),c=Or(ye.FIVE_MINUTES),l={protocol:jv},f={topic:o,expiry:c,relay:l,active:!1},h=rA({protocol:this.core.protocol,version:this.core.version,topic:o,symKey:i,relay:l,expiryTimestamp:c,methods:n?.methods});return this.core.expirer.set(o,c),await this.pairings.set(o,f),await this.core.relayer.subscribe(o),{topic:o,uri:h}},this.pair=async n=>{this.isInitialized(),this.isValidPair(n);const{topic:i,symKey:o,relay:c,expiryTimestamp:l,methods:f}=xm(n.uri);let h;if(this.pairings.keys.includes(i)&&(h=this.pairings.get(i),h.active))throw new Error(`Pairing already exists: ${i}. Please try again with a new connection URI.`);const g=l||Or(ye.FIVE_MINUTES),_={topic:i,relay:c,expiry:g,active:!1,methods:f};return this.core.expirer.set(i,g),await this.pairings.set(i,_),n.activatePairing&&await this.activate({topic:i}),this.events.emit(ra.create,_),this.core.crypto.keychain.has(i)||await this.core.crypto.setSymKey(o,i),await this.core.relayer.subscribe(i,{relay:c}),_},this.activate=async({topic:n})=>{this.isInitialized();const i=Or(ye.THIRTY_DAYS);this.core.expirer.set(n,i),await this.pairings.update(n,{active:!0,expiry:i})},this.ping=async n=>{this.isInitialized(),await this.isValidPing(n);const{topic:i}=n;if(this.pairings.keys.includes(i)){const o=await this.sendRequest(i,"wc_pairingPing",{}),{done:c,resolve:l,reject:f}=qs();this.events.once(wt("pairing_ping",o),({error:h})=>{h?f(h):l()}),await c()}},this.updateExpiry=async({topic:n,expiry:i})=>{this.isInitialized(),await this.pairings.update(n,{expiry:i})},this.updateMetadata=async({topic:n,metadata:i})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:i})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async n=>{this.isInitialized(),await this.isValidDisconnect(n);const{topic:i}=n;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",Ut("USER_DISCONNECTED")),await this.deletePairing(i))},this.sendRequest=async(n,i,o)=>{const c=ta(i,o),l=await this.core.crypto.encode(n,c),f=vc[i].req;return this.core.history.set(n,c),this.core.relayer.publish(n,l,f),c.id},this.sendResult=async(n,i,o)=>{const c=Wl(n,o),l=await this.core.crypto.encode(i,c),f=await this.core.history.get(i,n),h=vc[f.request.method].res;await this.core.relayer.publish(i,l,h),await this.core.history.resolve(c)},this.sendError=async(n,i,o)=>{const c=Vl(n,o),l=await this.core.crypto.encode(i,c),f=await this.core.history.get(i,n),h=vc[f.request.method]?vc[f.request.method].res:vc.unregistered_method.res;await this.core.relayer.publish(i,l,h),await this.core.history.resolve(c)},this.deletePairing=async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,Ut("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])},this.cleanup=async()=>{const n=this.pairings.getAll().filter(i=>os(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))},this.onRelayEventRequest=n=>{const{topic:i,payload:o}=n;switch(o.method){case"wc_pairingPing":return this.onPairingPingRequest(i,o);case"wc_pairingDelete":return this.onPairingDeleteRequest(i,o);default:return this.onUnknownRpcMethodRequest(i,o)}},this.onRelayEventResponse=async n=>{const{topic:i,payload:o}=n,c=(await this.core.history.get(i,o.id)).request.method;switch(c){case"wc_pairingPing":return this.onPairingPingResponse(i,o);default:return this.onUnknownRpcMethodResponse(c)}},this.onPairingPingRequest=async(n,i)=>{const{id:o}=i;try{this.isValidPing({topic:n}),await this.sendResult(o,n,!0),this.events.emit(ra.ping,{id:o,topic:n})}catch(c){await this.sendError(o,n,c),this.logger.error(c)}},this.onPairingPingResponse=(n,i)=>{const{id:o}=i;setTimeout(()=>{_i(i)?this.events.emit(wt("pairing_ping",o),{}):Mn(i)&&this.events.emit(wt("pairing_ping",o),{error:i.error})},500)},this.onPairingDeleteRequest=async(n,i)=>{const{id:o}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(ra.delete,{id:o,topic:n})}catch(c){await this.sendError(o,n,c),this.logger.error(c)}},this.onUnknownRpcMethodRequest=async(n,i)=>{const{id:o,method:c}=i;try{if(this.registeredMethods.includes(c))return;const l=Ut("WC_METHOD_UNSUPPORTED",c);await this.sendError(o,n,l),this.logger.error(l)}catch(l){await this.sendError(o,n,l),this.logger.error(l)}},this.onUnknownRpcMethodResponse=n=>{this.registeredMethods.includes(n)||this.logger.error(Ut("WC_METHOD_UNSUPPORTED",n))},this.isValidPair=n=>{var i;if(!tn(n)){const{message:c}=me("MISSING_OR_INVALID",`pair() params: ${n}`);throw new Error(c)}if(!hA(n.uri)){const{message:c}=me("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw new Error(c)}const o=xm(n.uri);if(!((i=o?.relay)!=null&&i.protocol)){const{message:c}=me("MISSING_OR_INVALID","pair() uri#relay-protocol");throw new Error(c)}if(!(o!=null&&o.symKey)){const{message:c}=me("MISSING_OR_INVALID","pair() uri#symKey");throw new Error(c)}if(o!=null&&o.expiryTimestamp&&ye.toMiliseconds(o?.expiryTimestamp)<Date.now()){const{message:c}=me("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(c)}},this.isValidPing=async n=>{if(!tn(n)){const{message:o}=me("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(o)}const{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidDisconnect=async n=>{if(!tn(n)){const{message:o}=me("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(o)}const{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidPairingTopic=async n=>{if(!ur(n,!1)){const{message:i}=me("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){const{message:i}=me("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(os(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:i}=me("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}},this.core=e,this.logger=sn(r,this.name),this.pairings=new Qs(this.core,this.logger,this.name,this.storagePrefix)}get context(){return nn(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=me("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(on.message,async e=>{const{topic:r,message:n}=e;if(!this.pairings.keys.includes(r)||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))return;const i=await this.core.crypto.decode(r,n);try{e0(i)?(this.core.history.set(r,i),this.onRelayEventRequest({topic:r,payload:i})):Gl(i)&&(await this.core.history.resolve(i),await this.onRelayEventResponse({topic:r,payload:i}),this.core.history.delete(r,i.id))}catch(o){this.logger.error(o)}})}registerExpirerEvents(){this.core.expirer.on($n.expired,async e=>{const{topic:r}=ng(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(ra.expire,{topic:r}))})}}class RI extends W7{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.records=new Map,this.events=new Dr.exports.EventEmitter,this.name=cI,this.version=lI,this.cached=[],this.initialized=!1,this.storagePrefix=hs,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(n,i,o)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:i,chainId:o}),this.records.has(i.id))return;const c={id:i.id,topic:n,request:{method:i.method,params:i.params||null},chainId:o,expiry:Or(ye.THIRTY_DAYS)};this.records.set(c.id,c),this.persist(),this.events.emit(ei.created,c)},this.resolve=async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;const i=await this.getRecord(n.id);typeof i.response>"u"&&(i.response=Mn(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.persist(),this.events.emit(ei.updated,i))},this.get=async(n,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:i}),await this.getRecord(i)),this.delete=(n,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(o=>{if(o.topic===n){if(typeof i<"u"&&o.id!==i)return;this.records.delete(o.id),this.events.emit(ei.deleted,o)}}),this.persist()},this.exists=async(n,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===n:!1),this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=sn(r,this.name)}get context(){return nn(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;const n={topic:r.topic,request:ta(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(n)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const r=this.records.get(e);if(!r){const{message:n}=me("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(ei.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=me("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(ei.created,e=>{const r=ei.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(ei.updated,e=>{const r=ei.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(ei.deleted,e=>{const r=ei.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(uc.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{ye.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(ei.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=me("NOT_INITIALIZED",this.name);throw new Error(e)}}}class LI extends Z7{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.expirations=new Map,this.events=new Dr.exports.EventEmitter,this.name=uI,this.version=hI,this.cached=[],this.initialized=!1,this.storagePrefix=hs,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=n=>{try{const i=this.formatTarget(n);return typeof this.getExpiration(i)<"u"}catch{return!1}},this.set=(n,i)=>{this.isInitialized();const o=this.formatTarget(n),c={target:o,expiry:i};this.expirations.set(o,c),this.checkExpiry(o,c),this.events.emit($n.created,{target:o,expiration:c})},this.get=n=>{this.isInitialized();const i=this.formatTarget(n);return this.getExpiration(i)},this.del=n=>{if(this.isInitialized(),this.has(n)){const i=this.formatTarget(n),o=this.getExpiration(i);this.expirations.delete(i),this.events.emit($n.deleted,{target:i,expiration:o})}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=sn(r,this.name)}get context(){return nn(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return R8(e);if(typeof e=="number")return L8(e);const{message:r}=me("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit($n.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=me("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const r=this.expirations.get(e);if(!r){const{message:n}=me("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(n),new Error(n)}return r}checkExpiry(e,r){const{expiry:n}=r;ye.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit($n.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(uc.pulse,()=>this.checkExpirations()),this.events.on($n.created,e=>{const r=$n.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on($n.expired,e=>{const r=$n.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on($n.deleted,e=>{const r=$n.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=me("NOT_INITIALIZED",this.name);throw new Error(e)}}}class BI extends X7{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.name=o0,this.initialized=!1,this.queue=[],this.verifyDisabled=!1,this.init=async n=>{if(this.verifyDisabled||Uo()||!Fo())return;const i=this.getVerifyUrl(n?.verifyUrl);this.verifyUrl!==i&&this.removeIframe(),this.verifyUrl=i;try{await this.createIframe()}catch(o){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(o)}if(!this.initialized){this.removeIframe(),this.verifyUrl=a0;try{await this.createIframe()}catch(o){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(o),this.verifyDisabled=!0}}},this.register=async n=>{this.initialized?this.sendPost(n.attestationId):(this.addToQueue(n.attestationId),await this.init())},this.resolve=async n=>{if(this.isDevEnv)return"";const i=this.getVerifyUrl(n?.verifyUrl);let o;try{o=await this.fetchAttestation(n.attestationId,i)}catch(c){this.logger.info(`failed to resolve attestation: ${n.attestationId} from url: ${i}`),this.logger.info(c),o=await this.fetchAttestation(n.attestationId,a0)}return o},this.fetchAttestation=async(n,i)=>{this.logger.info(`resolving attestation: ${n} from url: ${i}`);const o=this.startAbortTimer(ye.ONE_SECOND*2),c=await fetch(`${i}/attestation/${n}`,{signal:this.abortController.signal});return clearTimeout(o),c.status===200?await c.json():void 0},this.addToQueue=n=>{this.queue.push(n)},this.processQueue=()=>{this.queue.length!==0&&(this.queue.forEach(n=>this.sendPost(n)),this.queue=[])},this.sendPost=n=>{var i;try{if(!this.iframe)return;(i=this.iframe.contentWindow)==null||i.postMessage(n,"*"),this.logger.info(`postMessage sent: ${n} ${this.verifyUrl}`)}catch{}},this.createIframe=async()=>{let n;const i=o=>{o.data==="verify_ready"&&(this.onInit(),window.removeEventListener("message",i),n())};await Promise.race([new Promise(o=>{const c=document.getElementById(o0);if(c)return this.iframe=c,this.onInit(),o();window.addEventListener("message",i);const l=document.createElement("iframe");l.id=o0,l.src=`${this.verifyUrl}/${this.projectId}`,l.style.display="none",document.body.append(l),this.iframe=l,n=o}),new Promise((o,c)=>setTimeout(()=>{window.removeEventListener("message",i),c("verify iframe load timeout")},ye.toMiliseconds(ye.FIVE_SECONDS)))])},this.onInit=()=>{this.initialized=!0,this.processQueue()},this.removeIframe=()=>{this.iframe&&(this.iframe.remove(),this.iframe=void 0,this.initialized=!1)},this.getVerifyUrl=n=>{let i=n||na;return fI.includes(i)||(this.logger.info(`verify url: ${i}, not included in trusted list, assigning default: ${na}`),i=na),i},this.logger=sn(r,this.name),this.verifyUrl=na,this.abortController=new AbortController,this.isDevEnv=Wa()&&process.env.IS_VITEST}get context(){return nn(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),ye.toMiliseconds(e))}}class UI extends ex{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.context=dI,this.registerDeviceToken=async n=>{const{clientId:i,token:o,notificationType:c,enableEncrypted:l=!1}=n,f=`${pI}/${this.projectId}/clients`;await f9(f,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:i,type:c,token:o,always_raw:l})})},this.logger=sn(r,this.context)}}var FI=Object.defineProperty,Qv=Object.getOwnPropertySymbols,jI=Object.prototype.hasOwnProperty,kI=Object.prototype.propertyIsEnumerable,Jv=(t,e,r)=>e in t?FI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Zv=(t,e)=>{for(var r in e||(e={}))jI.call(e,r)&&Jv(t,r,e[r]);if(Qv)for(var r of Qv(e))kI.call(e,r)&&Jv(t,r,e[r]);return t};class l0 extends K7{constructor(e){var r;super(e),this.protocol=Uv,this.version=US,this.name=s0,this.events=new Dr.exports.EventEmitter,this.initialized=!1,this.on=(c,l)=>this.events.on(c,l),this.once=(c,l)=>this.events.once(c,l),this.off=(c,l)=>this.events.off(c,l),this.removeListener=(c,l)=>this.events.removeListener(c,l),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||kv,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const n=Hl({level:typeof e?.logger=="string"&&e.logger?e.logger:FS.logger}),{logger:i,chunkLoggerController:o}=H7({opts:n,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=o,(r=this.logChunkController)!=null&&r.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var c,l;(c=this.logChunkController)!=null&&c.downloadLogsBlobInBrowser&&((l=this.logChunkController)==null||l.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=sn(i,this.name),this.heartbeat=new jf,this.crypto=new mI(this,this.logger,e?.keychain),this.history=new RI(this,this.logger),this.expirer=new LI(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new g7(Zv(Zv({},jS),e?.storageOptions)),this.relayer=new MI({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new NI(this,this.logger),this.verify=new BI(this.projectId||"",this.logger),this.echoClient=new UI(this.projectId||"",this.logger)}static async init(e){const r=new l0(e);await r.initialize();const n=await r.crypto.getClientId();return await r.storage.setItem(rI,n),r}get context(){return nn(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async 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}}}const qI=l0,Xv="wc",ew=2,tw="client",u0=`${Xv}@${ew}:${tw}:`,h0={name:tw,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},rw="WALLETCONNECT_DEEPLINK_CHOICE",zI="proposal",nw="Proposal expired",HI="session",ia=ye.SEVEN_DAYS,KI="engine",Tr={wc_sessionPropose:{req:{ttl:ye.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:ye.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:ye.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:ye.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:ye.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:ye.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:ye.ONE_DAY,prompt:!1,tag:1104},res:{ttl:ye.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:ye.ONE_DAY,prompt:!1,tag:1106},res:{ttl:ye.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:ye.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:ye.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:ye.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:ye.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:ye.ONE_DAY,prompt:!1,tag:1112},res:{ttl:ye.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:ye.ONE_DAY,prompt:!1,tag:1114},res:{ttl:ye.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:ye.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:ye.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:ye.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:ye.FIVE_MINUTES,prompt:!1,tag:1119}}},f0={min:ye.FIVE_MINUTES,max:ye.SEVEN_DAYS},Ai={idle:"IDLE",active:"ACTIVE"},WI="request",VI=["wc_sessionPropose","wc_sessionRequest","wc_authRequest"],GI="wc",YI="auth",QI="authKeys",JI="pairingTopics",ZI="requests",Ql=`${GI}@${1.5}:${YI}:`,Jl=`${Ql}:PUB_KEY`;var XI=Object.defineProperty,eD=Object.defineProperties,tD=Object.getOwnPropertyDescriptors,iw=Object.getOwnPropertySymbols,rD=Object.prototype.hasOwnProperty,nD=Object.prototype.propertyIsEnumerable,sw=(t,e,r)=>e in t?XI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,vr=(t,e)=>{for(var r in e||(e={}))rD.call(e,r)&&sw(t,r,e[r]);if(iw)for(var r of iw(e))nD.call(e,r)&&sw(t,r,e[r]);return t},Js=(t,e)=>eD(t,tD(e));class iD extends rx{constructor(e){super(e),this.name=KI,this.events=new Dr.exports,this.initialized=!1,this.requestQueue={state:Ai.idle,queue:[]},this.sessionRequestQueue={state:Ai.idle,queue:[]},this.requestQueueDelay=ye.ONE_SECOND,this.expectedPairingMethodMap=new Map,this.recentlyDeletedMap=new Map,this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),this.client.core.pairing.register({methods:Object.keys(Tr)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},ye.toMiliseconds(this.requestQueueDelay)))},this.connect=async r=>{await this.isInitialized();const n=Js(vr({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n);const{pairingTopic:i,requiredNamespaces:o,optionalNamespaces:c,sessionProperties:l,relays:f}=n;let h=i,g,_=!1;try{h&&(_=this.client.core.pairing.pairings.get(h).active)}catch(M){throw this.client.logger.error(`connect() -> pairing.get(${h}) failed`),M}if(!h||!_){const{topic:M,uri:U}=await this.client.core.pairing.create();h=M,g=U}if(!h){const{message:M}=me("NO_MATCHING_KEY",`connect() pairing topic: ${h}`);throw new Error(M)}const E=await this.client.core.crypto.generateKeyPair(),x=Tr.wc_sessionPropose.req.ttl||ye.FIVE_MINUTES,I=Or(x),k=vr({requiredNamespaces:o,optionalNamespaces:c,relays:f??[{protocol:jv}],proposer:{publicKey:E,metadata:this.client.metadata},expiryTimestamp:I,pairingTopic:h},l&&{sessionProperties:l}),{reject:W,resolve:Y,done:B}=qs(x,nw);this.events.once(wt("session_connect"),async({error:M,session:U})=>{if(M)W(M);else if(U){U.self.publicKey=E;const F=Js(vr({},U),{pairingTopic:k.pairingTopic,requiredNamespaces:k.requiredNamespaces,optionalNamespaces:k.optionalNamespaces});await this.client.session.set(U.topic,F),await this.setExpiry(U.topic,U.expiry),h&&await this.client.core.pairing.updateMetadata({topic:h,metadata:U.peer.metadata}),this.cleanupDuplicatePairings(F),Y(F)}});const z=await this.sendRequest({topic:h,method:"wc_sessionPropose",params:k,throwOnFailedPublish:!0});return await this.setProposal(z,vr({id:z},k)),{uri:g,approval:B}},this.pair=async r=>{await this.isInitialized();try{return await this.client.core.pairing.pair(r)}catch(n){throw this.client.logger.error("pair() failed"),n}},this.approve=async r=>{await this.isInitialized();try{await this.isValidApprove(r)}catch(B){throw this.client.logger.error("approve() -> isValidApprove() failed"),B}const{id:n,relayProtocol:i,namespaces:o,sessionProperties:c,sessionConfig:l}=r;let f;try{f=this.client.proposal.get(n)}catch(B){throw this.client.logger.error(`approve() -> proposal.get(${n}) failed`),B}const{pairingTopic:h,proposer:g,requiredNamespaces:_,optionalNamespaces:E}=f,x=await this.client.core.crypto.generateKeyPair(),I=g.publicKey,k=await this.client.core.crypto.generateSharedKey(x,I),W=vr(vr({relay:{protocol:i??"irn"},namespaces:o,controller:{publicKey:x,metadata:this.client.metadata},expiry:Or(ia)},c&&{sessionProperties:c}),l&&{sessionConfig:l});await this.client.core.relayer.subscribe(k);const Y=Js(vr({},W),{topic:k,requiredNamespaces:_,optionalNamespaces:E,pairingTopic:h,acknowledged:!1,self:W.controller,peer:{publicKey:g.publicKey,metadata:g.metadata},controller:x});await this.client.session.set(k,Y);try{await this.sendResult({id:n,topic:h,result:{relay:{protocol:i??"irn"},responderPublicKey:x},throwOnFailedPublish:!0}),await this.sendRequest({topic:k,method:"wc_sessionSettle",params:W,throwOnFailedPublish:!0})}catch(B){throw this.client.logger.error(B),this.client.session.delete(k,Ut("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(k),B}return await this.client.core.pairing.updateMetadata({topic:h,metadata:g.metadata}),await this.client.proposal.delete(n,Ut("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:h}),await this.setExpiry(k,Or(ia)),{topic:k,acknowledged:()=>new Promise(B=>setTimeout(()=>B(this.client.session.get(k)),500))}},this.reject=async r=>{await this.isInitialized();try{await this.isValidReject(r)}catch(c){throw this.client.logger.error("reject() -> isValidReject() failed"),c}const{id:n,reason:i}=r;let o;try{o=this.client.proposal.get(n).pairingTopic}catch(c){throw this.client.logger.error(`reject() -> proposal.get(${n}) failed`),c}o&&(await this.sendError({id:n,topic:o,error:i,rpcOpts:Tr.wc_sessionPropose.reject}),await this.client.proposal.delete(n,Ut("USER_DISCONNECTED")))},this.update=async r=>{await this.isInitialized();try{await this.isValidUpdate(r)}catch(_){throw this.client.logger.error("update() -> isValidUpdate() failed"),_}const{topic:n,namespaces:i}=r,{done:o,resolve:c,reject:l}=qs(),f=us(),h=Ys().toString(),g=this.client.session.get(n).namespaces;return this.events.once(wt("session_update",f),({error:_})=>{_?l(_):c()}),await this.client.session.update(n,{namespaces:i}),await this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:f,relayRpcId:h}).catch(_=>{this.client.logger.error(_),this.client.session.update(n,{namespaces:g}),l(_)}),{acknowledged:o}},this.extend=async r=>{await this.isInitialized();try{await this.isValidExtend(r)}catch(f){throw this.client.logger.error("extend() -> isValidExtend() failed"),f}const{topic:n}=r,i=us(),{done:o,resolve:c,reject:l}=qs();return this.events.once(wt("session_extend",i),({error:f})=>{f?l(f):c()}),await this.setExpiry(n,Or(ia)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(f=>{l(f)}),{acknowledged:o}},this.request=async r=>{await this.isInitialized();try{await this.isValidRequest(r)}catch(x){throw this.client.logger.error("request() -> isValidRequest() failed"),x}const{chainId:n,request:i,topic:o,expiry:c=Tr.wc_sessionRequest.req.ttl}=r,l=this.client.session.get(o),f=us(),h=Ys().toString(),{done:g,resolve:_,reject:E}=qs(c,"Request expired. Please try again.");return this.events.once(wt("session_request",f),({error:x,result:I})=>{x?E(x):_(I)}),await Promise.all([new Promise(async x=>{await this.sendRequest({clientRpcId:f,relayRpcId:h,topic:o,method:"wc_sessionRequest",params:{request:Js(vr({},i),{expiryTimestamp:Or(c)}),chainId:n},expiry:c,throwOnFailedPublish:!0}).catch(I=>E(I)),this.client.events.emit("session_request_sent",{topic:o,request:i,chainId:n,id:f}),x()}),new Promise(async x=>{var I;if(!((I=l.sessionConfig)!=null&&I.disableDeepLink)){const k=await U8(this.client.core.storage,rw);B8({id:f,topic:o,wcDeepLink:k})}x()}),g()]).then(x=>x[2])},this.respond=async r=>{await this.isInitialized(),await this.isValidRespond(r);const{topic:n,response:i}=r,{id:o}=i;_i(i)?await this.sendResult({id:o,topic:n,result:i.result,throwOnFailedPublish:!0}):Mn(i)&&await this.sendError({id:o,topic:n,error:i.error}),this.cleanupAfterResponse(r)},this.ping=async r=>{await this.isInitialized();try{await this.isValidPing(r)}catch(i){throw this.client.logger.error("ping() -> isValidPing() failed"),i}const{topic:n}=r;if(this.client.session.keys.includes(n)){const i=us(),o=Ys().toString(),{done:c,resolve:l,reject:f}=qs();this.events.once(wt("session_ping",i),({error:h})=>{h?f(h):l()}),await Promise.all([this.sendRequest({topic:n,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:i,relayRpcId:o}),c()])}else this.client.core.pairing.pairings.keys.includes(n)&&await this.client.core.pairing.ping({topic:n})},this.emit=async r=>{await this.isInitialized(),await this.isValidEmit(r);const{topic:n,event:i,chainId:o}=r,c=Ys().toString();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:i,chainId:o},throwOnFailedPublish:!0,relayRpcId:c})},this.disconnect=async r=>{await this.isInitialized(),await this.isValidDisconnect(r);const{topic:n}=r;if(this.client.session.keys.includes(n))await this.sendRequest({topic:n,method:"wc_sessionDelete",params:Ut("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:n,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(n))await this.client.core.pairing.disconnect({topic:n});else{const{message:i}=me("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(i)}},this.find=r=>(this.isInitialized(),this.client.session.getAll().filter(n=>lA(n,r))),this.getPendingSessionRequests=()=>this.client.pendingRequest.getAll(),this.authenticate=async r=>{this.isInitialized(),this.isValidAuthenticate(r);const{chains:n,statement:i="",uri:o,domain:c,nonce:l,type:f,exp:h,nbf:g,methods:_=[],expiry:E}=r,x=[...r.resources||[]],{topic:I,uri:k}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"]});this.client.logger.info({message:"Generated new pairing",pairing:{topic:I,uri:k}});const W=await this.client.core.crypto.generateKeyPair(),Y=Tl(W);if(await Promise.all([this.client.auth.authKeys.set(Jl,{responseTopic:Y,publicKey:W}),this.client.auth.pairingTopics.set(Y,{topic:Y,pairingTopic:I})]),await this.client.core.relayer.subscribe(Y),this.client.logger.info(`sending request to new pairing topic: ${I}`),_.length>0){const{namespace:d}=ml(n[0]);let p=TE(d,"request",_);$l(x)&&(p=RE(p,x.pop())),x.push(p)}const B=E&&E>Tr.wc_sessionAuthenticate.req.ttl?E:Tr.wc_sessionAuthenticate.req.ttl,z={authPayload:{type:f??"caip122",chains:n,statement:i,aud:o,domain:c,version:"1",nonce:l,iat:new Date().toISOString(),exp:h,nbf:g,resources:x},requester:{publicKey:W,metadata:this.client.metadata},expiryTimestamp:Or(B)},M={eip155:{chains:n,methods:[...new Set(["personal_sign",..._])],events:["chainChanged","accountsChanged"]}},U={requiredNamespaces:{},optionalNamespaces:M,relays:[{protocol:"irn"}],pairingTopic:I,proposer:{publicKey:W,metadata:this.client.metadata},expiryTimestamp:Or(Tr.wc_sessionPropose.req.ttl)},{done:F,resolve:m,reject:$}=qs(B,"Request expired"),te=async({error:d,session:p})=>{if(this.events.off(wt("session_request",ne),ee),d)$(d);else if(p){p.self.publicKey=W,await this.client.session.set(p.topic,p),await this.setExpiry(p.topic,p.expiry),I&&await this.client.core.pairing.updateMetadata({topic:I,metadata:p.peer.metadata});const b=this.client.session.get(p.topic);await this.deleteProposal(de),m({session:b})}},ee=async d=>{if(await this.deletePendingAuthRequest(ne,{message:"fulfilled",code:0}),d.error){const C=Ut("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return d.error.code===C.code?void 0:(this.events.off(wt("session_connect"),te),$(d.error.message))}await this.deleteProposal(de),this.events.off(wt("session_connect"),te);const{cacaos:p,responder:b}=d.result,D=[],O=[];for(const C of p){await hm({cacao:C,projectId:this.client.core.projectId})||(this.client.logger.error(C,"Signature verification failed"),$(Ut("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:v}=C,N=$l(v.resources),oe=[um(v.iss)],pe=Pl(v.iss);if(N){const A=pm(N),re=gm(N);D.push(...A),oe.push(...re)}for(const A of oe)O.push(`${A}:${pe}`)}const T=await this.client.core.crypto.generateSharedKey(W,b.publicKey);let L;D.length>0&&(L={topic:T,acknowledged:!0,self:{publicKey:W,metadata:this.client.metadata},peer:b,controller:b.publicKey,expiry:Or(ia),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:I,namespaces:Sm([...new Set(D)],[...new Set(O)])},await this.client.core.relayer.subscribe(T),await this.client.session.set(T,L),L=this.client.session.get(T)),m({auths:p,session:L})},ne=us(),de=us();this.events.once(wt("session_connect"),te),this.events.once(wt("session_request",ne),ee);try{await Promise.all([this.sendRequest({topic:I,method:"wc_sessionAuthenticate",params:z,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:ne}),this.sendRequest({topic:I,method:"wc_sessionPropose",params:U,expiry:Tr.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:de})])}catch(d){throw this.events.off(wt("session_connect"),te),this.events.off(wt("session_request",ne),ee),d}return await this.setProposal(de,vr({id:de},U)),await this.setAuthRequest(ne,{request:Js(vr({},z),{verifyContext:{}}),pairingTopic:I}),{uri:k,response:F}},this.approveSessionAuthenticate=async r=>{this.isInitialized();const{id:n,auths:i}=r,o=this.getPendingAuthRequest(n);if(!o)throw new Error(`Could not find pending auth request with id ${n}`);const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),f=Tl(c),h={type:ji,receiverPublicKey:c,senderPublicKey:l},g=[],_=[];for(const I of i){if(!await hm({cacao:I,projectId:this.client.core.projectId})){const z=Ut("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:f,error:z,encodeOpts:h}),new Error(z.message)}const{p:k}=I,W=$l(k.resources),Y=[um(k.iss)],B=Pl(k.iss);if(W){const z=pm(W),M=gm(W);g.push(...z),Y.push(...M)}for(const z of Y)_.push(`${z}:${B}`)}const E=await this.client.core.crypto.generateSharedKey(l,c);let x;return g?.length>0&&(x={topic:E,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:Or(ia),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:"",namespaces:Sm([...new Set(g)],[...new Set(_)])},await this.client.core.relayer.subscribe(E),await this.client.session.set(E,x)),await this.sendResult({topic:f,id:n,result:{cacaos:i,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0}),await this.client.auth.requests.delete(n,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),{session:x}},this.rejectSessionAuthenticate=async r=>{await this.isInitialized();const{id:n,reason:i}=r,o=this.getPendingAuthRequest(n);if(!o)throw new Error(`Could not find pending auth request with id ${n}`);const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),f=Tl(c),h={type:ji,receiverPublicKey:c,senderPublicKey:l};await this.sendError({id:n,topic:f,error:i,encodeOpts:h,rpcOpts:Tr.wc_sessionAuthenticate.reject}),await this.client.auth.requests.delete(n,{message:"rejected",code:0}),await this.client.proposal.delete(n,Ut("USER_DISCONNECTED"))},this.formatAuthMessage=r=>{this.isInitialized();const{request:n,iss:i}=r;return fm(n,i)},this.cleanupDuplicatePairings=async r=>{if(r.pairingTopic)try{const n=this.client.core.pairing.pairings.get(r.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(o=>{var c,l;return((c=o.peerMetadata)==null?void 0:c.url)&&((l=o.peerMetadata)==null?void 0:l.url)===r.peer.metadata.url&&o.topic&&o.topic!==n.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(o=>this.client.core.pairing.disconnect({topic:o.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}},this.deleteSession=async r=>{var n;const{topic:i,expirerHasDeleted:o=!1,emitEvent:c=!0,id:l=0}=r,{self:f}=this.client.session.get(i);await this.client.core.relayer.unsubscribe(i),await this.client.session.delete(i,Ut("USER_DISCONNECTED")),this.addToRecentlyDeleted(i,"session"),this.client.core.crypto.keychain.has(f.publicKey)&&await this.client.core.crypto.deleteKeyPair(f.publicKey),this.client.core.crypto.keychain.has(i)&&await this.client.core.crypto.deleteSymKey(i),o||this.client.core.expirer.del(i),this.client.core.storage.removeItem(rw).catch(h=>this.client.logger.warn(h)),this.getPendingSessionRequests().forEach(h=>{h.topic===i&&this.deletePendingSessionRequest(h.id,Ut("USER_DISCONNECTED"))}),i===((n=this.sessionRequestQueue.queue[0])==null?void 0:n.topic)&&(this.sessionRequestQueue.state=Ai.idle),c&&this.client.events.emit("session_delete",{id:l,topic:i})},this.deleteProposal=async(r,n)=>{await Promise.all([this.client.proposal.delete(r,Ut("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")},this.deletePendingSessionRequest=async(r,n,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(o=>o.id!==r),i&&(this.sessionRequestQueue.state=Ai.idle,this.client.events.emit("session_request_expire",{id:r}))},this.deletePendingAuthRequest=async(r,n,i=!1)=>{await Promise.all([this.client.auth.requests.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)])},this.setExpiry=async(r,n)=>{this.client.session.keys.includes(r)&&(this.client.core.expirer.set(r,n),await this.client.session.update(r,{expiry:n}))},this.setProposal=async(r,n)=>{this.client.core.expirer.set(r,Or(Tr.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,n)},this.setAuthRequest=async(r,n)=>{const{request:i,pairingTopic:o}=n;this.client.core.expirer.set(r,i.expiryTimestamp),await this.client.auth.requests.set(r,{authPayload:i.authPayload,requester:i.requester,expiryTimestamp:i.expiryTimestamp,id:r,pairingTopic:o,verifyContext:i.verifyContext})},this.setPendingSessionRequest=async r=>{const{id:n,topic:i,params:o,verifyContext:c}=r,l=o.request.expiryTimestamp||Or(Tr.wc_sessionRequest.req.ttl);this.client.core.expirer.set(n,l),await this.client.pendingRequest.set(n,{id:n,topic:i,params:o,verifyContext:c})},this.sendRequest=async r=>{const{topic:n,method:i,params:o,expiry:c,relayRpcId:l,clientRpcId:f,throwOnFailedPublish:h}=r,g=ta(i,o,f);if(Fo()&&VI.includes(i)){const x=Ws(JSON.stringify(g));this.client.core.verify.register({attestationId:x})}let _;try{_=await this.client.core.crypto.encode(n,g)}catch(x){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),x}const E=Tr[i].req;return c&&(E.ttl=c),l&&(E.id=l),this.client.core.history.set(n,g),h?(E.internal=Js(vr({},E.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,_,E)):this.client.core.relayer.publish(n,_,E).catch(x=>this.client.logger.error(x)),g.id},this.sendResult=async r=>{const{id:n,topic:i,result:o,throwOnFailedPublish:c,encodeOpts:l}=r,f=Wl(n,o);let h;try{h=await this.client.core.crypto.encode(i,f,l)}catch(E){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),E}let g;try{g=await this.client.core.history.get(i,n)}catch(E){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${n}) failed`),E}const _=Tr[g.request.method].res;c?(_.internal=Js(vr({},_.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,h,_)):this.client.core.relayer.publish(i,h,_).catch(E=>this.client.logger.error(E)),await this.client.core.history.resolve(f)},this.sendError=async r=>{const{id:n,topic:i,error:o,encodeOpts:c,rpcOpts:l}=r,f=Vl(n,o);let h;try{h=await this.client.core.crypto.encode(i,f,c)}catch(E){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),E}let g;try{g=await this.client.core.history.get(i,n)}catch(E){throw this.client.logger.error(`sendError() -> history.get(${i}, ${n}) failed`),E}const _=l||Tr[g.request.method].res;this.client.core.relayer.publish(i,h,_),await this.client.core.history.resolve(f)},this.cleanup=async()=>{const r=[],n=[];this.client.session.getAll().forEach(i=>{let o=!1;os(i.expiry)&&(o=!0),this.client.core.crypto.keychain.has(i.topic)||(o=!0),o&&r.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{os(i.expiryTimestamp)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession({topic:i})),...n.map(i=>this.deleteProposal(i))])},this.onRelayEventRequest=async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state===Ai.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=Ai.active;const r=this.requestQueue.queue.shift();if(r)try{this.processRequest(r),await new Promise(n=>setTimeout(n,300))}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=Ai.idle},this.processRequest=r=>{const{topic:n,payload:i}=r,o=i.method;if(!this.shouldIgnorePairingRequest({topic:n,requestMethod:o}))switch(o){case"wc_sessionPropose":return this.onSessionProposeRequest(n,i);case"wc_sessionSettle":return this.onSessionSettleRequest(n,i);case"wc_sessionUpdate":return this.onSessionUpdateRequest(n,i);case"wc_sessionExtend":return this.onSessionExtendRequest(n,i);case"wc_sessionPing":return this.onSessionPingRequest(n,i);case"wc_sessionDelete":return this.onSessionDeleteRequest(n,i);case"wc_sessionRequest":return this.onSessionRequest(n,i);case"wc_sessionEvent":return this.onSessionEventRequest(n,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateRequest(n,i);default:return this.client.logger.info(`Unsupported request method ${o}`)}},this.onRelayEventResponse=async r=>{const{topic:n,payload:i}=r,o=(await this.client.core.history.get(n,i.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(n,i);case"wc_sessionSettle":return this.onSessionSettleResponse(n,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,i);case"wc_sessionExtend":return this.onSessionExtendResponse(n,i);case"wc_sessionPing":return this.onSessionPingResponse(n,i);case"wc_sessionRequest":return this.onSessionRequestResponse(n,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(n,i);default:return this.client.logger.info(`Unsupported response method ${o}`)}},this.onRelayEventUnknownPayload=r=>{const{topic:n}=r,{message:i}=me("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)},this.shouldIgnorePairingRequest=r=>{const{topic:n,requestMethod:i}=r,o=this.expectedPairingMethodMap.get(n);return!o||o.includes(i)?!1:!!(o.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)},this.onSessionProposeRequest=async(r,n)=>{const{params:i,id:o}=n;try{this.isValidConnect(vr({},n.params));const c=i.expiryTimestamp||Or(Tr.wc_sessionPropose.req.ttl),l=vr({id:o,pairingTopic:r,expiryTimestamp:c},i);await this.setProposal(o,l);const f=Ws(JSON.stringify(n)),h=await this.getVerifyContext(f,l.proposer.metadata);this.client.events.emit("session_proposal",{id:o,params:l,verifyContext:h})}catch(c){await this.sendError({id:o,topic:r,error:c,rpcOpts:Tr.wc_sessionPropose.autoReject}),this.client.logger.error(c)}},this.onSessionProposeResponse=async(r,n)=>{const{id:i}=n;if(_i(n)){const{result:o}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const c=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:c});const l=c.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:l});const f=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:f});const h=await this.client.core.crypto.generateSharedKey(l,f);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:h});const g=await this.client.core.relayer.subscribe(h);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:g}),await this.client.core.pairing.activate({topic:r})}else if(Mn(n)){await this.client.proposal.delete(i,Ut("USER_DISCONNECTED"));const o=wt("session_connect");if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(wt("session_connect"),{error:n.error})}},this.onSessionSettleRequest=async(r,n)=>{const{id:i,params:o}=n;try{this.isValidSessionSettleRequest(o);const{relay:c,controller:l,expiry:f,namespaces:h,sessionProperties:g,sessionConfig:_}=n.params,E=vr(vr({topic:r,relay:c,expiry:f,namespaces:h,acknowledged:!0,pairingTopic:"",requiredNamespaces:{},optionalNamespaces:{},controller:l.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:l.publicKey,metadata:l.metadata}},g&&{sessionProperties:g}),_&&{sessionConfig:_});await this.sendResult({id:n.id,topic:r,result:!0,throwOnFailedPublish:!0});const x=wt("session_connect");if(this.events.listenerCount(x)===0)throw new Error(`emitting ${x} without any listeners 997`);this.events.emit(wt("session_connect"),{session:E})}catch(c){await this.sendError({id:i,topic:r,error:c}),this.client.logger.error(c)}},this.onSessionSettleResponse=async(r,n)=>{const{id:i}=n;_i(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(wt("session_approve",i),{})):Mn(n)&&(await this.client.session.delete(r,Ut("USER_DISCONNECTED")),this.events.emit(wt("session_approve",i),{error:n.error}))},this.onSessionUpdateRequest=async(r,n)=>{const{params:i,id:o}=n;try{const c=`${r}_session_update`,l=ac.get(c);if(l&&this.isRequestOutOfSync(l,o)){this.client.logger.info(`Discarding out of sync request - ${o}`),this.sendError({id:o,topic:r,error:Ut("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(vr({topic:r},i));try{ac.set(c,o),await this.client.session.update(r,{namespaces:i.namespaces}),await this.sendResult({id:o,topic:r,result:!0,throwOnFailedPublish:!0})}catch(f){throw ac.delete(c),f}this.client.events.emit("session_update",{id:o,topic:r,params:i})}catch(c){await this.sendError({id:o,topic:r,error:c}),this.client.logger.error(c)}},this.isRequestOutOfSync=(r,n)=>parseInt(n.toString().slice(0,-3))<=parseInt(r.toString().slice(0,-3)),this.onSessionUpdateResponse=(r,n)=>{const{id:i}=n,o=wt("session_update",i);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners`);_i(n)?this.events.emit(wt("session_update",i),{}):Mn(n)&&this.events.emit(wt("session_update",i),{error:n.error})},this.onSessionExtendRequest=async(r,n)=>{const{id:i}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,Or(ia)),await this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:i,topic:r})}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}},this.onSessionExtendResponse=(r,n)=>{const{id:i}=n,o=wt("session_extend",i);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners`);_i(n)?this.events.emit(wt("session_extend",i),{}):Mn(n)&&this.events.emit(wt("session_extend",i),{error:n.error})},this.onSessionPingRequest=async(r,n)=>{const{id:i}=n;try{this.isValidPing({topic:r}),await this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:i,topic:r})}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}},this.onSessionPingResponse=(r,n)=>{const{id:i}=n,o=wt("session_ping",i);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners`);setTimeout(()=>{_i(n)?this.events.emit(wt("session_ping",i),{}):Mn(n)&&this.events.emit(wt("session_ping",i),{error:n.error})},500)},this.onSessionDeleteRequest=async(r,n)=>{const{id:i}=n;try{this.isValidDisconnect({topic:r,reason:n.params}),await Promise.all([new Promise(o=>{this.client.core.relayer.once(on.publish,async()=>{o(await this.deleteSession({topic:r,id:i}))})}),this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:r,error:Ut("USER_DISCONNECTED")})])}catch(o){this.client.logger.error(o)}},this.onSessionRequest=async(r,n)=>{var i;const{id:o,params:c}=n;try{await this.isValidRequest(vr({topic:r},c));const l=Ws(JSON.stringify(ta("wc_sessionRequest",c,o))),f=this.client.session.get(r),h=await this.getVerifyContext(l,f.peer.metadata),g={id:o,topic:r,params:c,verifyContext:h};await this.setPendingSessionRequest(g),(i=this.client.signConfig)!=null&&i.disableRequestQueue?this.emitSessionRequest(g):(this.addSessionRequestToSessionRequestQueue(g),this.processSessionRequestQueue())}catch(l){await this.sendError({id:o,topic:r,error:l}),this.client.logger.error(l)}},this.onSessionRequestResponse=(r,n)=>{const{id:i}=n,o=wt("session_request",i);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners`);_i(n)?this.events.emit(wt("session_request",i),{result:n.result}):Mn(n)&&this.events.emit(wt("session_request",i),{error:n.error})},this.onSessionEventRequest=async(r,n)=>{const{id:i,params:o}=n;try{const c=`${r}_session_event_${o.event.name}`,l=ac.get(c);if(l&&this.isRequestOutOfSync(l,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(vr({topic:r},o)),this.client.events.emit("session_event",{id:i,topic:r,params:o}),ac.set(c,i)}catch(c){await this.sendError({id:i,topic:r,error:c}),this.client.logger.error(c)}},this.onSessionAuthenticateResponse=(r,n)=>{const{id:i}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:n}),_i(n)?this.events.emit(wt("session_request",i),{result:n.result}):Mn(n)&&this.events.emit(wt("session_request",i),{error:n.error})},this.onSessionAuthenticateRequest=async(r,n)=>{try{const{requester:i,authPayload:o,expiryTimestamp:c}=n.params,l=Ws(JSON.stringify(n)),f=await this.getVerifyContext(l,this.client.metadata),h={requester:i,pairingTopic:r,id:n.id,authPayload:o,verifyContext:f,expiryTimestamp:c};await this.setAuthRequest(n.id,{request:h,pairingTopic:r}),this.client.events.emit("session_authenticate",{topic:r,params:n.params,id:n.id})}catch(i){this.client.logger.error(i);const o=n.params.requester.publicKey,c=await this.client.core.crypto.generateKeyPair(),l={type:ji,receiverPublicKey:o,senderPublicKey:c};await this.sendError({id:n.id,topic:r,error:i,encodeOpts:l,rpcOpts:Tr.wc_sessionAuthenticate.autoReject})}},this.addSessionRequestToSessionRequestQueue=r=>{this.sessionRequestQueue.queue.push(r)},this.cleanupAfterResponse=r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Ai.idle,this.processSessionRequestQueue()},ye.toMiliseconds(this.requestQueueDelay))},this.cleanupPendingSentRequestsForTopic=({topic:r,error:n})=>{const i=this.client.core.history.pending;i.length>0&&i.filter(o=>o.topic===r&&o.request.method==="wc_sessionRequest").forEach(o=>{const c=o.request.id,l=wt("session_request",c);if(this.events.listenerCount(l)===0)throw new Error(`emitting ${l} without any listeners`);this.events.emit(wt("session_request",o.request.id),{error:n})})},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===Ai.active){this.client.logger.info("session request queue is already active.");return}const r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=Ai.active,this.emitSessionRequest(r)}catch(n){this.client.logger.error(n)}},this.emitSessionRequest=r=>{this.client.events.emit("session_request",r)},this.onPairingCreated=r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;const n=this.client.proposal.getAll().find(i=>i.pairingTopic===r.topic);n&&this.onSessionProposeRequest(r.topic,ta("wc_sessionPropose",{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties},n.id))},this.isValidConnect=async r=>{if(!tn(r)){const{message:f}=me("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(f)}const{pairingTopic:n,requiredNamespaces:i,optionalNamespaces:o,sessionProperties:c,relays:l}=r;if(Hr(n)||await this.isValidPairingTopic(n),!_A(l,!0)){const{message:f}=me("MISSING_OR_INVALID",`connect() relays: ${l}`);throw new Error(f)}!Hr(i)&&oc(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!Hr(o)&&oc(o)!==0&&this.validateNamespaces(o,"optionalNamespaces"),Hr(c)||this.validateSessionProps(c,"sessionProperties")},this.validateNamespaces=(r,n)=>{const i=bA(r,"connect()",n);if(i)throw new Error(i.message)},this.isValidApprove=async r=>{if(!tn(r))throw new Error(me("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:n,namespaces:i,relayProtocol:o,sessionProperties:c}=r;this.checkRecentlyDeleted(n),await this.isValidProposalId(n);const l=this.client.proposal.get(n),f=Rf(i,"approve()");if(f)throw new Error(f.message);const h=Mm(l.requiredNamespaces,i,"approve()");if(h)throw new Error(h.message);if(!ur(o,!0)){const{message:g}=me("MISSING_OR_INVALID",`approve() relayProtocol: ${o}`);throw new Error(g)}Hr(c)||this.validateSessionProps(c,"sessionProperties")},this.isValidReject=async r=>{if(!tn(r)){const{message:o}=me("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(o)}const{id:n,reason:i}=r;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!AA(i)){const{message:o}=me("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(o)}},this.isValidSessionSettleRequest=r=>{if(!tn(r)){const{message:h}=me("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(h)}const{relay:n,controller:i,namespaces:o,expiry:c}=r;if(!Cm(n)){const{message:h}=me("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(h)}const l=pA(i,"onSessionSettleRequest()");if(l)throw new Error(l.message);const f=Rf(o,"onSessionSettleRequest()");if(f)throw new Error(f.message);if(os(c)){const{message:h}=me("EXPIRED","onSessionSettleRequest()");throw new Error(h)}},this.isValidUpdate=async r=>{if(!tn(r)){const{message:f}=me("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(f)}const{topic:n,namespaces:i}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);const o=this.client.session.get(n),c=Rf(i,"update()");if(c)throw new Error(c.message);const l=Mm(o.requiredNamespaces,i,"update()");if(l)throw new Error(l.message)},this.isValidExtend=async r=>{if(!tn(r)){const{message:i}=me("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(i)}const{topic:n}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)},this.isValidRequest=async r=>{if(!tn(r)){const{message:f}=me("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(f)}const{topic:n,request:i,chainId:o,expiry:c}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);const{namespaces:l}=this.client.session.get(n);if(!Om(l,o)){const{message:f}=me("MISSING_OR_INVALID",`request() chainId: ${o}`);throw new Error(f)}if(!xA(i)){const{message:f}=me("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(f)}if(!DA(l,o,i.method)){const{message:f}=me("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(f)}if(c&&!PA(c,f0)){const{message:f}=me("MISSING_OR_INVALID",`request() expiry: ${c}. Expiry must be a number (in seconds) between ${f0.min} and ${f0.max}`);throw new Error(f)}},this.isValidRespond=async r=>{var n;if(!tn(r)){const{message:c}=me("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(c)}const{topic:i,response:o}=r;try{await this.isValidSessionTopic(i)}catch(c){throw(n=r?.response)!=null&&n.id&&this.cleanupAfterResponse(r),c}if(!SA(o)){const{message:c}=me("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(o)}`);throw new Error(c)}},this.isValidPing=async r=>{if(!tn(r)){const{message:i}=me("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.isValidEmit=async r=>{if(!tn(r)){const{message:l}=me("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(l)}const{topic:n,event:i,chainId:o}=r;await this.isValidSessionTopic(n);const{namespaces:c}=this.client.session.get(n);if(!Om(c,o)){const{message:l}=me("MISSING_OR_INVALID",`emit() chainId: ${o}`);throw new Error(l)}if(!IA(i)){const{message:l}=me("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(l)}if(!CA(c,o,i.name)){const{message:l}=me("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(l)}},this.isValidDisconnect=async r=>{if(!tn(r)){const{message:i}=me("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.isValidAuthenticate=r=>{const{chains:n,uri:i,domain:o,nonce:c}=r;if(!Array.isArray(n)||n.length===0)throw new Error("chains is required and must be a non-empty array");if(!ur(i,!1))throw new Error("uri is required parameter");if(!ur(o,!1))throw new Error("domain is required parameter");if(!ur(c,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(f=>ml(f).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:l}=ml(n[0]);if(l!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")},this.getVerifyContext=async(r,n)=>{const i={verified:{verifyUrl:n.verifyUrl||na,validation:"UNKNOWN",origin:n.url||""}};try{const o=await this.client.core.verify.resolve({attestationId:r,verifyUrl:n.verifyUrl});o&&(i.verified.origin=o.origin,i.verified.isScam=o.isScam,i.verified.validation=o.origin===new URL(n.url).origin?"VALID":"INVALID")}catch(o){this.client.logger.info(o)}return this.client.logger.info(`Verify context: ${JSON.stringify(i)}`),i},this.validateSessionProps=(r,n)=>{Object.values(r).forEach(i=>{if(!ur(i,!1)){const{message:o}=me("MISSING_OR_INVALID",`${n} must be in Record<string, string> format. Received: ${JSON.stringify(i)}`);throw new Error(o)}})},this.getPendingAuthRequest=r=>{const n=this.client.auth.requests.get(r);return typeof n=="object"?n:void 0},this.addToRecentlyDeleted=(r,n)=>{if(this.recentlyDeletedMap.set(r,n),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let i=0;const o=this.recentlyDeletedLimit/2;for(const c of this.recentlyDeletedMap.keys()){if(i++>=o)break;this.recentlyDeletedMap.delete(c)}}},this.checkRecentlyDeleted=r=>{const n=this.recentlyDeletedMap.get(r);if(n){const{message:i}=me("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${r}`);throw new Error(i)}}}async isInitialized(){if(!this.initialized){const{message:e}=me("NOT_INITIALIZED",this.name);throw new Error(e)}await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(on.message,async e=>{const{topic:r,message:n}=e,{publicKey:i}=this.client.auth.authKeys.keys.includes(Jl)?this.client.auth.authKeys.get(Jl):{responseTopic:void 0,publicKey:void 0},o=await this.client.core.crypto.decode(r,n,{receiverPublicKey:i});try{e0(o)?(this.client.core.history.set(r,o),this.onRelayEventRequest({topic:r,payload:o})):Gl(o)?(await this.client.core.history.resolve(o),await this.onRelayEventResponse({topic:r,payload:o}),this.client.core.history.delete(r,o.id)):this.onRelayEventUnknownPayload({topic:r,payload:o})}catch(c){this.client.logger.error(c)}})}registerExpirerEvents(){this.client.core.expirer.on($n.expired,async e=>{const{topic:r,id:n}=ng(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,me("EXPIRED"),!0);if(n&&this.client.auth.requests.keys.includes(n))return await this.deletePendingAuthRequest(n,me("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}registerPairingEvents(){this.client.core.pairing.events.on(ra.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(ra.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!ur(e,!1)){const{message:r}=me("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:r}=me("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(os(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=me("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!ur(e,!1)){const{message:r}=me("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:r}=me("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(os(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=me("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=me("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(ur(e,!1)){const{message:r}=me("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=me("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!EA(e)){const{message:r}=me("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=me("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(os(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=me("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class sD extends Qs{constructor(e,r){super(e,r,zI,u0),this.core=e,this.logger=r}}class oD extends Qs{constructor(e,r){super(e,r,HI,u0),this.core=e,this.logger=r}}class aD extends Qs{constructor(e,r){super(e,r,WI,u0,n=>n.id),this.core=e,this.logger=r}}class cD extends Qs{constructor(e,r){super(e,r,QI,Ql,()=>Jl),this.core=e,this.logger=r}}class lD extends Qs{constructor(e,r){super(e,r,JI,Ql),this.core=e,this.logger=r}}class uD extends Qs{constructor(e,r){super(e,r,ZI,Ql,n=>n.id),this.core=e,this.logger=r}}class hD{constructor(e,r){this.core=e,this.logger=r,this.authKeys=new cD(this.core,this.logger),this.pairingTopics=new lD(this.core,this.logger),this.requests=new uD(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}class d0 extends tx{constructor(e){super(e),this.protocol=Xv,this.version=ew,this.name=h0.name,this.events=new Dr.exports.EventEmitter,this.on=(n,i)=>this.events.on(n,i),this.once=(n,i)=>this.events.once(n,i),this.off=(n,i)=>this.events.off(n,i),this.removeListener=(n,i)=>this.events.removeListener(n,i),this.removeAllListeners=n=>this.events.removeAllListeners(n),this.connect=async n=>{try{return await this.engine.connect(n)}catch(i){throw this.logger.error(i.message),i}},this.pair=async n=>{try{return await this.engine.pair(n)}catch(i){throw this.logger.error(i.message),i}},this.approve=async n=>{try{return await this.engine.approve(n)}catch(i){throw this.logger.error(i.message),i}},this.reject=async n=>{try{return await this.engine.reject(n)}catch(i){throw this.logger.error(i.message),i}},this.update=async n=>{try{return await this.engine.update(n)}catch(i){throw this.logger.error(i.message),i}},this.extend=async n=>{try{return await this.engine.extend(n)}catch(i){throw this.logger.error(i.message),i}},this.request=async n=>{try{return await this.engine.request(n)}catch(i){throw this.logger.error(i.message),i}},this.respond=async n=>{try{return await this.engine.respond(n)}catch(i){throw this.logger.error(i.message),i}},this.ping=async n=>{try{return await this.engine.ping(n)}catch(i){throw this.logger.error(i.message),i}},this.emit=async n=>{try{return await this.engine.emit(n)}catch(i){throw this.logger.error(i.message),i}},this.disconnect=async n=>{try{return await this.engine.disconnect(n)}catch(i){throw this.logger.error(i.message),i}},this.find=n=>{try{return this.engine.find(n)}catch(i){throw this.logger.error(i.message),i}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}},this.authenticate=async n=>{try{return await this.engine.authenticate(n)}catch(i){throw this.logger.error(i.message),i}},this.formatAuthMessage=n=>{try{return this.engine.formatAuthMessage(n)}catch(i){throw this.logger.error(i.message),i}},this.approveSessionAuthenticate=async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}},this.rejectSessionAuthenticate=async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}},this.name=e?.name||h0.name,this.metadata=e?.metadata||M8(),this.signConfig=e?.signConfig;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:yi(Hl({level:e?.logger||h0.logger}));this.core=e?.core||new qI(e),this.logger=sn(r,this.name),this.session=new oD(this.core,this.logger),this.proposal=new sD(this.core,this.logger),this.pendingRequest=new aD(this.core,this.logger),this.engine=new iD(this),this.auth=new hD(this.core,this.logger)}static async init(e){const r=new d0(e);return await r.initialize(),r}get context(){return nn(this.logger)}get pairing(){return this.core.pairing.pairings}validateMetadata(e){if(!e.name)throw new Error("name is required value in metadata");if(!e.description)throw new Error("description is required value in metadata");if(!e.url)throw new Error("url is required value in metadata")}async initialize(){this.logger.trace("Initialized");try{await this.validateMetadata(this.metadata),await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.engine.init(),await this.auth.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}}}var p0={exports:{}};(function(t,e){var r=typeof self<"u"?self:jr,n=function(){function o(){this.fetch=!1,this.DOMException=r.DOMException}return o.prototype=r,new o}();(function(o){(function(c){var l={searchParams:"URLSearchParams"in o,iterable:"Symbol"in o&&"iterator"in Symbol,blob:"FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in o,arrayBuffer:"ArrayBuffer"in o};function f(p){return p&&DataView.prototype.isPrototypeOf(p)}if(l.arrayBuffer)var h=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],g=ArrayBuffer.isView||function(p){return p&&h.indexOf(Object.prototype.toString.call(p))>-1};function _(p){if(typeof p!="string"&&(p=String(p)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(p))throw new TypeError("Invalid character in header field name");return p.toLowerCase()}function E(p){return typeof p!="string"&&(p=String(p)),p}function x(p){var b={next:function(){var D=p.shift();return{done:D===void 0,value:D}}};return l.iterable&&(b[Symbol.iterator]=function(){return b}),b}function I(p){this.map={},p instanceof I?p.forEach(function(b,D){this.append(D,b)},this):Array.isArray(p)?p.forEach(function(b){this.append(b[0],b[1])},this):p&&Object.getOwnPropertyNames(p).forEach(function(b){this.append(b,p[b])},this)}I.prototype.append=function(p,b){p=_(p),b=E(b);var D=this.map[p];this.map[p]=D?D+", "+b:b},I.prototype.delete=function(p){delete this.map[_(p)]},I.prototype.get=function(p){return p=_(p),this.has(p)?this.map[p]:null},I.prototype.has=function(p){return this.map.hasOwnProperty(_(p))},I.prototype.set=function(p,b){this.map[_(p)]=E(b)},I.prototype.forEach=function(p,b){for(var D in this.map)this.map.hasOwnProperty(D)&&p.call(b,this.map[D],D,this)},I.prototype.keys=function(){var p=[];return this.forEach(function(b,D){p.push(D)}),x(p)},I.prototype.values=function(){var p=[];return this.forEach(function(b){p.push(b)}),x(p)},I.prototype.entries=function(){var p=[];return this.forEach(function(b,D){p.push([D,b])}),x(p)},l.iterable&&(I.prototype[Symbol.iterator]=I.prototype.entries);function k(p){if(p.bodyUsed)return Promise.reject(new TypeError("Already read"));p.bodyUsed=!0}function W(p){return new Promise(function(b,D){p.onload=function(){b(p.result)},p.onerror=function(){D(p.error)}})}function Y(p){var b=new FileReader,D=W(b);return b.readAsArrayBuffer(p),D}function B(p){var b=new FileReader,D=W(b);return b.readAsText(p),D}function z(p){for(var b=new Uint8Array(p),D=new Array(b.length),O=0;O<b.length;O++)D[O]=String.fromCharCode(b[O]);return D.join("")}function M(p){if(p.slice)return p.slice(0);var b=new Uint8Array(p.byteLength);return b.set(new Uint8Array(p)),b.buffer}function U(){return this.bodyUsed=!1,this._initBody=function(p){this._bodyInit=p,p?typeof p=="string"?this._bodyText=p:l.blob&&Blob.prototype.isPrototypeOf(p)?this._bodyBlob=p:l.formData&&FormData.prototype.isPrototypeOf(p)?this._bodyFormData=p:l.searchParams&&URLSearchParams.prototype.isPrototypeOf(p)?this._bodyText=p.toString():l.arrayBuffer&&l.blob&&f(p)?(this._bodyArrayBuffer=M(p.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):l.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(p)||g(p))?this._bodyArrayBuffer=M(p):this._bodyText=p=Object.prototype.toString.call(p):this._bodyText="",this.headers.get("content-type")||(typeof p=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):l.searchParams&&URLSearchParams.prototype.isPrototypeOf(p)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},l.blob&&(this.blob=function(){var p=k(this);if(p)return p;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?k(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(Y)}),this.text=function(){var p=k(this);if(p)return p;if(this._bodyBlob)return B(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(z(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},l.formData&&(this.formData=function(){return this.text().then(te)}),this.json=function(){return this.text().then(JSON.parse)},this}var F=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function m(p){var b=p.toUpperCase();return F.indexOf(b)>-1?b:p}function $(p,b){b=b||{};var D=b.body;if(p instanceof $){if(p.bodyUsed)throw new TypeError("Already read");this.url=p.url,this.credentials=p.credentials,b.headers||(this.headers=new I(p.headers)),this.method=p.method,this.mode=p.mode,this.signal=p.signal,!D&&p._bodyInit!=null&&(D=p._bodyInit,p.bodyUsed=!0)}else this.url=String(p);if(this.credentials=b.credentials||this.credentials||"same-origin",(b.headers||!this.headers)&&(this.headers=new I(b.headers)),this.method=m(b.method||this.method||"GET"),this.mode=b.mode||this.mode||null,this.signal=b.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&D)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(D)}$.prototype.clone=function(){return new $(this,{body:this._bodyInit})};function te(p){var b=new FormData;return p.trim().split("&").forEach(function(D){if(D){var O=D.split("="),T=O.shift().replace(/\+/g," "),L=O.join("=").replace(/\+/g," ");b.append(decodeURIComponent(T),decodeURIComponent(L))}}),b}function ee(p){var b=new I,D=p.replace(/\r?\n[\t ]+/g," ");return D.split(/\r?\n/).forEach(function(O){var T=O.split(":"),L=T.shift().trim();if(L){var C=T.join(":").trim();b.append(L,C)}}),b}U.call($.prototype);function ne(p,b){b||(b={}),this.type="default",this.status=b.status===void 0?200:b.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in b?b.statusText:"OK",this.headers=new I(b.headers),this.url=b.url||"",this._initBody(p)}U.call(ne.prototype),ne.prototype.clone=function(){return new ne(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new I(this.headers),url:this.url})},ne.error=function(){var p=new ne(null,{status:0,statusText:""});return p.type="error",p};var de=[301,302,303,307,308];ne.redirect=function(p,b){if(de.indexOf(b)===-1)throw new RangeError("Invalid status code");return new ne(null,{status:b,headers:{location:p}})},c.DOMException=o.DOMException;try{new c.DOMException}catch{c.DOMException=function(b,D){this.message=b,this.name=D;var O=Error(b);this.stack=O.stack},c.DOMException.prototype=Object.create(Error.prototype),c.DOMException.prototype.constructor=c.DOMException}function d(p,b){return new Promise(function(D,O){var T=new $(p,b);if(T.signal&&T.signal.aborted)return O(new c.DOMException("Aborted","AbortError"));var L=new XMLHttpRequest;function C(){L.abort()}L.onload=function(){var v={status:L.status,statusText:L.statusText,headers:ee(L.getAllResponseHeaders()||"")};v.url="responseURL"in L?L.responseURL:v.headers.get("X-Request-URL");var N="response"in L?L.response:L.responseText;D(new ne(N,v))},L.onerror=function(){O(new TypeError("Network request failed"))},L.ontimeout=function(){O(new TypeError("Network request failed"))},L.onabort=function(){O(new c.DOMException("Aborted","AbortError"))},L.open(T.method,T.url,!0),T.credentials==="include"?L.withCredentials=!0:T.credentials==="omit"&&(L.withCredentials=!1),"responseType"in L&&l.blob&&(L.responseType="blob"),T.headers.forEach(function(v,N){L.setRequestHeader(N,v)}),T.signal&&(T.signal.addEventListener("abort",C),L.onreadystatechange=function(){L.readyState===4&&T.signal.removeEventListener("abort",C)}),L.send(typeof T._bodyInit>"u"?null:T._bodyInit)})}return d.polyfill=!0,o.fetch||(o.fetch=d,o.Headers=I,o.Request=$,o.Response=ne),c.Headers=I,c.Request=$,c.Response=ne,c.fetch=d,Object.defineProperty(c,"__esModule",{value:!0}),c})({})})(n),n.fetch.ponyfill=!0,delete n.fetch.polyfill;var i=n;e=i.fetch,e.default=i.fetch,e.fetch=i.fetch,e.Headers=i.Headers,e.Request=i.Request,e.Response=i.Response,t.exports=e})(p0,p0.exports);var ow=t3(p0.exports),fD=Object.defineProperty,dD=Object.defineProperties,pD=Object.getOwnPropertyDescriptors,aw=Object.getOwnPropertySymbols,gD=Object.prototype.hasOwnProperty,mD=Object.prototype.propertyIsEnumerable,cw=(t,e,r)=>e in t?fD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,lw=(t,e)=>{for(var r in e||(e={}))gD.call(e,r)&&cw(t,r,e[r]);if(aw)for(var r of aw(e))mD.call(e,r)&&cw(t,r,e[r]);return t},uw=(t,e)=>dD(t,pD(e));const vD={Accept:"application/json","Content-Type":"application/json"},wD="POST",hw={headers:vD,method:wD},fw=10;class fs{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new Dr.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!pv(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=r}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(e){this.isAvailable||await this.register();try{const r=ki(e),n=await(await ow(this.url,uw(lw({},hw),{body:r}))).json();this.onPayload({data:n})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!pv(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",o=>{this.resetMaxListeners(),i(o)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return i(new Error("HTTP connection is missing or invalid"));n()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const r=ki({id:1,jsonrpc:"2.0",method:"test",params:[]});await ow(e,uw(lw({},hw),{body:r}))}this.onOpen()}catch(r){const n=this.parseError(r);throw this.events.emit("register_error",n),this.onClose(),n}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?lc(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),o=Vl(e,i);this.events.emit("payload",o)}parseError(e,r=this.url){return cv(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>fw&&this.events.setMaxListeners(fw)}}const dw="error",yD="wss://relay.walletconnect.com",bD="wc",_D="universal_provider",pw=`${bD}@2:${_D}:`,ED="https://rpc.walletconnect.com/v1/",Ki={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var yc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},g0={exports:{}};/**
|
|
43
|
+
***************************************************************************** */var Jf=function(t,e){return Jf=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)n.hasOwnProperty(i)&&(r[i]=n[i])},Jf(t,e)};function Cx(t,e){Jf(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var Zf=function(){return Zf=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},Zf.apply(this,arguments)};function Ox(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function Mx(t,e,r,n){var i=arguments.length,o=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,c;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(t,e,r,n);else for(var l=t.length-1;l>=0;l--)(c=t[l])&&(o=(i<3?c(o):i>3?c(e,r,o):c(e,r))||o);return i>3&&o&&Object.defineProperty(e,r,o),o}function Px(t,e){return function(r,n){e(r,n,t)}}function $x(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function Tx(t,e,r,n){function i(o){return o instanceof r?o:new r(function(c){c(o)})}return new(r||(r=Promise))(function(o,c){function l(g){try{h(n.next(g))}catch(_){c(_)}}function f(g){try{h(n.throw(g))}catch(_){c(_)}}function h(g){g.done?o(g.value):i(g.value).then(l,f)}h((n=n.apply(t,e||[])).next())})}function Nx(t,e){var r={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,i,o,c;return c={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(c[Symbol.iterator]=function(){return this}),c;function l(h){return function(g){return f([h,g])}}function f(h){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(o=h[0]&2?i.return:h[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,h[1])).done)return o;switch(i=0,o&&(h=[h[0]&2,o.value]),h[0]){case 0:case 1:o=h;break;case 4:return r.label++,{value:h[1],done:!1};case 5:r.label++,i=h[1],h=[0];continue;case 7:h=r.ops.pop(),r.trys.pop();continue;default:if(o=r.trys,!(o=o.length>0&&o[o.length-1])&&(h[0]===6||h[0]===2)){r=0;continue}if(h[0]===3&&(!o||h[1]>o[0]&&h[1]<o[3])){r.label=h[1];break}if(h[0]===6&&r.label<o[1]){r.label=o[1],o=h;break}if(o&&r.label<o[2]){r.label=o[2],r.ops.push(h);break}o[2]&&r.ops.pop(),r.trys.pop();continue}h=e.call(t,r)}catch(g){h=[6,g],i=0}finally{n=o=0}if(h[0]&5)throw h[1];return{value:h[0]?h[1]:void 0,done:!0}}}function Rx(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function Lx(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function Xf(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function uv(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,o=[],c;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(l){c={error:l}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(c)throw c.error}}return o}function Bx(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(uv(arguments[e]));return t}function Ux(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),i=0,e=0;e<r;e++)for(var o=arguments[e],c=0,l=o.length;c<l;c++,i++)n[i]=o[c];return n}function gc(t){return this instanceof gc?(this.v=t,this):new gc(t)}function Fx(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),i,o=[];return i={},c("next"),c("throw"),c("return"),i[Symbol.asyncIterator]=function(){return this},i;function c(E){n[E]&&(i[E]=function(x){return new Promise(function(I,k){o.push([E,x,I,k])>1||l(E,x)})})}function l(E,x){try{f(n[E](x))}catch(I){_(o[0][3],I)}}function f(E){E.value instanceof gc?Promise.resolve(E.value.v).then(h,g):_(o[0][2],E)}function h(E){l("next",E)}function g(E){l("throw",E)}function _(E,x){E(x),o.shift(),o.length&&l(o[0][0],o[0][1])}}function jx(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,o){e[i]=t[i]?function(c){return(r=!r)?{value:gc(t[i](c)),done:i==="return"}:o?o(c):c}:o}}function kx(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof Xf=="function"?Xf(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(o){r[o]=t[o]&&function(c){return new Promise(function(l,f){c=t[o](c),i(l,f,c.done,c.value)})}}function i(o,c,l,f){Promise.resolve(f).then(function(h){o({value:h,done:l})},c)}}function qx(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function zx(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function Hx(t){return t&&t.__esModule?t:{default:t}}function Kx(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function Wx(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var Vx=Object.freeze({__proto__:null,__extends:Cx,get __assign(){return Zf},__rest:Ox,__decorate:Mx,__param:Px,__metadata:$x,__awaiter:Tx,__generator:Nx,__createBinding:Rx,__exportStar:Lx,__values:Xf,__read:uv,__spread:Bx,__spreadArrays:Ux,__await:gc,__asyncGenerator:Fx,__asyncDelegator:jx,__asyncValues:kx,__makeTemplateObject:qx,__importStar:zx,__importDefault:Hx,__classPrivateFieldGet:Kx,__classPrivateFieldSet:Wx}),Gx=il(Vx),qi={},hv;function Yx(){if(hv)return qi;hv=1,Object.defineProperty(qi,"__esModule",{value:!0}),qi.isBrowserCryptoAvailable=qi.getSubtleCrypto=qi.getBrowerCrypto=void 0;function t(){return jr?.crypto||jr?.msCrypto||{}}qi.getBrowerCrypto=t;function e(){const n=t();return n.subtle||n.webkitSubtle}qi.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return qi.isBrowserCryptoAvailable=r,qi}var zi={},fv;function Qx(){if(fv)return zi;fv=1,Object.defineProperty(zi,"__esModule",{value:!0}),zi.isBrowser=zi.isNode=zi.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}zi.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}zi.isNode=e;function r(){return!t()&&!e()}return zi.isBrowser=r,zi}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Gx;e.__exportStar(Yx(),t),e.__exportStar(Qx(),t)})(lv);function us(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Ys(t=6){return BigInt(us(t))}function ta(t,e,r){return{id:r||us(),jsonrpc:"2.0",method:t,params:e}}function Wl(t,e){return{id:t,jsonrpc:"2.0",result:e}}function Vl(t,e,r){return{id:t,jsonrpc:"2.0",error:Jx(e,r)}}function Jx(t,e){return typeof t>"u"?av(sv):(typeof t=="string"&&(t=Object.assign(Object.assign({},av(Qf)),{message:t})),typeof e<"u"&&(t.data=e),Ix(t.code)&&(t=Dx(t.code)),t)}class Zx{}class Xx extends Zx{constructor(){super()}}class e9 extends Xx{constructor(e){super()}}const t9="^https?:",r9="^wss?:";function n9(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function dv(t,e){const r=n9(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function pv(t){return dv(t,t9)}function gv(t){return dv(t,r9)}function i9(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function mv(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function e0(t){return mv(t)&&"method"in t}function Gl(t){return mv(t)&&(_i(t)||Mn(t))}function _i(t){return"result"in t}function Mn(t){return"error"in t}class Hi extends e9{constructor(e){super(e),this.events=new Dr.exports.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(ta(e.method,e.params||[],e.id||Ys().toString()),r)}async requestStrict(e,r){return new Promise(async(n,i)=>{if(!this.connection.connected)try{await this.open()}catch(o){i(o)}this.events.on(`${e.id}`,o=>{Mn(o)?i(o.error):n(o.result)});try{await this.connection.send(e,r)}catch(o){i(o)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),Gl(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}}const s9=()=>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"),o9=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",vv=t=>t.split("?")[0],wv=10,a9=s9();class c9{constructor(e){if(this.url=e,this.events=new Dr.exports.EventEmitter,this.registering=!1,!gv(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=n=>{this.onClose(n),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(ki(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!gv(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",o=>{this.resetMaxListeners(),i(o)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return i(new Error("WebSocket connection is missing or invalid"));n(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,n)=>{const i=new URLSearchParams(e).get("origin"),o=lv.isReactNative()?{headers:{origin:i}}:{rejectUnauthorized:!i9(e)},c=new a9(e,[],o);o9()?c.onerror=l=>{const f=l;n(this.emitError(f.error))}:c.on("error",l=>{n(this.emitError(l))}),c.onopen=()=>{this.onOpen(c),r(c)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?lc(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),o=Vl(e,i);this.events.emit("payload",o)}parseError(e,r=this.url){return cv(e,vv(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>wv&&this.events.setMaxListeners(wv)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${vv(this.url)}`));return this.events.emit("register_error",r),r}}var t0={exports:{}};(function(t,e){var r=200,n="__lodash_hash_undefined__",i=1,o=2,c=9007199254740991,l="[object Arguments]",f="[object Array]",h="[object AsyncFunction]",g="[object Boolean]",_="[object Date]",E="[object Error]",x="[object Function]",I="[object GeneratorFunction]",k="[object Map]",W="[object Number]",Y="[object Null]",B="[object Object]",z="[object Promise]",M="[object Proxy]",U="[object RegExp]",F="[object Set]",m="[object String]",$="[object Symbol]",te="[object Undefined]",ee="[object WeakMap]",ne="[object ArrayBuffer]",de="[object DataView]",d="[object Float32Array]",p="[object Float64Array]",b="[object Int8Array]",D="[object Int16Array]",O="[object Int32Array]",T="[object Uint8Array]",L="[object Uint8ClampedArray]",C="[object Uint16Array]",v="[object Uint32Array]",N=/[\\^$.*+?()[\]{}|]/g,oe=/^\[object .+?Constructor\]$/,pe=/^(?:0|[1-9]\d*)$/,A={};A[d]=A[p]=A[b]=A[D]=A[O]=A[T]=A[L]=A[C]=A[v]=!0,A[l]=A[f]=A[ne]=A[g]=A[de]=A[_]=A[E]=A[x]=A[k]=A[W]=A[B]=A[U]=A[F]=A[m]=A[ee]=!1;var re=typeof jr=="object"&&jr&&jr.Object===Object&&jr,q=typeof self=="object"&&self&&self.Object===Object&&self,H=re||q||Function("return this")(),V=e&&!e.nodeType&&e,w=V&&!0&&t&&!t.nodeType&&t,j=w&&w.exports===V,ie=j&&re.process,he=function(){try{return ie&&ie.binding&&ie.binding("util")}catch{}}(),le=he&&he.isTypedArray;function Oe(K,J){for(var fe=-1,Se=K==null?0:K.length,Vt=0,ot=[];++fe<Se;){var Zt=K[fe];J(Zt,fe,K)&&(ot[Vt++]=Zt)}return ot}function Pe(K,J){for(var fe=-1,Se=J.length,Vt=K.length;++fe<Se;)K[Vt+fe]=J[fe];return K}function Ie(K,J){for(var fe=-1,Se=K==null?0:K.length;++fe<Se;)if(J(K[fe],fe,K))return!0;return!1}function Mt(K,J){for(var fe=-1,Se=Array(K);++fe<K;)Se[fe]=J(fe);return Se}function ze(K){return function(J){return K(J)}}function Ce(K,J){return K.has(J)}function Fe(K,J){return K?.[J]}function Ee(K){var J=-1,fe=Array(K.size);return K.forEach(function(Se,Vt){fe[++J]=[Vt,Se]}),fe}function Ae(K,J){return function(fe){return K(J(fe))}}function Ge(K){var J=-1,fe=Array(K.size);return K.forEach(function(Se){fe[++J]=Se}),fe}var be=Array.prototype,xe=Function.prototype,Be=Object.prototype,_e=H["__core-js_shared__"],Me=xe.toString,je=Be.hasOwnProperty,$e=function(){var K=/[^.]+$/.exec(_e&&_e.keys&&_e.keys.IE_PROTO||"");return K?"Symbol(src)_1."+K:""}(),Te=Be.toString,lt=RegExp("^"+Me.call(je).replace(N,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Re=j?H.Buffer:void 0,Ne=H.Symbol,nr=H.Uint8Array,dt=Be.propertyIsEnumerable,Et=be.splice,ir=Ne?Ne.toStringTag:void 0,St=Object.getOwnPropertySymbols,Ot=Re?Re.isBuffer:void 0,Vr=Ae(Object.keys,Object),Ye=bn(H,"DataView"),He=bn(H,"Map"),Rt=bn(H,"Promise"),Qe=bn(H,"Set"),Ve=bn(H,"WeakMap"),Pt=bn(Object,"create"),Xe=Yi(Ye),et=Yi(He),Lt=Yi(Rt),tt=Yi(Qe),Je=Yi(Ve),Ft=Ne?Ne.prototype:void 0,Ze=Ft?Ft.valueOf:void 0;function ke(K){var J=-1,fe=K==null?0:K.length;for(this.clear();++J<fe;){var Se=K[J];this.set(Se[0],Se[1])}}function Ht(){this.__data__=Pt?Pt(null):{},this.size=0}function rt(K){var J=this.has(K)&&delete this.__data__[K];return this.size-=J?1:0,J}function jt(K){var J=this.__data__;if(Pt){var fe=J[K];return fe===n?void 0:fe}return je.call(J,K)?J[K]:void 0}function ti(K){var J=this.__data__;return Pt?J[K]!==void 0:je.call(J,K)}function kt(K,J){var fe=this.__data__;return this.size+=this.has(K)?0:1,fe[K]=Pt&&J===void 0?n:J,this}ke.prototype.clear=Ht,ke.prototype.delete=rt,ke.prototype.get=jt,ke.prototype.has=ti,ke.prototype.set=kt;function vt(K){var J=-1,fe=K==null?0:K.length;for(this.clear();++J<fe;){var Se=K[J];this.set(Se[0],Se[1])}}function Nn(){this.__data__=[],this.size=0}function Rn(K){var J=this.__data__,fe=bo(J,K);if(fe<0)return!1;var Se=J.length-1;return fe==Se?J.pop():Et.call(J,fe,1),--this.size,!0}function Ln(K){var J=this.__data__,fe=bo(J,K);return fe<0?void 0:J[fe][1]}function Bn(K){return bo(this.__data__,K)>-1}function Un(K,J){var fe=this.__data__,Se=bo(fe,K);return Se<0?(++this.size,fe.push([K,J])):fe[Se][1]=J,this}vt.prototype.clear=Nn,vt.prototype.delete=Rn,vt.prototype.get=Ln,vt.prototype.has=Bn,vt.prototype.set=Un;function xr(K){var J=-1,fe=K==null?0:K.length;for(this.clear();++J<fe;){var Se=K[J];this.set(Se[0],Se[1])}}function Ci(){this.size=0,this.__data__={hash:new ke,map:new(He||vt),string:new ke}}function fo(K){var J=Cs(this,K).delete(K);return this.size-=J?1:0,J}function Oi(K){return Cs(this,K).get(K)}function po(K){return Cs(this,K).has(K)}function go(K,J){var fe=Cs(this,K),Se=fe.size;return fe.set(K,J),this.size+=fe.size==Se?0:1,this}xr.prototype.clear=Ci,xr.prototype.delete=fo,xr.prototype.get=Oi,xr.prototype.has=po,xr.prototype.set=go;function Mi(K){var J=-1,fe=K==null?0:K.length;for(this.__data__=new xr;++J<fe;)this.add(K[J])}function Is(K){return this.__data__.set(K,n),this}function Ds(K){return this.__data__.has(K)}Mi.prototype.add=Mi.prototype.push=Is,Mi.prototype.has=Ds;function Gr(K){var J=this.__data__=new vt(K);this.size=J.size}function mo(){this.__data__=new vt,this.size=0}function vo(K){var J=this.__data__,fe=J.delete(K);return this.size=J.size,fe}function wo(K){return this.__data__.get(K)}function yo(K){return this.__data__.has(K)}function Pu(K,J){var fe=this.__data__;if(fe instanceof vt){var Se=fe.__data__;if(!He||Se.length<r-1)return Se.push([K,J]),this.size=++fe.size,this;fe=this.__data__=new xr(Se)}return fe.set(K,J),this.size=fe.size,this}Gr.prototype.clear=mo,Gr.prototype.delete=vo,Gr.prototype.get=wo,Gr.prototype.has=yo,Gr.prototype.set=Pu;function $u(K,J){var fe=Sa(K),Se=!fe&&Hu(K),Vt=!fe&&!Se&&kc(K),ot=!fe&&!Se&&!Vt&&Vu(K),Zt=fe||Se||Vt||ot,gr=Zt?Mt(K.length,String):[],It=gr.length;for(var Gt in K)(J||je.call(K,Gt))&&!(Zt&&(Gt=="length"||Vt&&(Gt=="offset"||Gt=="parent")||ot&&(Gt=="buffer"||Gt=="byteLength"||Gt=="byteOffset")||Fu(Gt,It)))&&gr.push(Gt);return gr}function bo(K,J){for(var fe=K.length;fe--;)if(zu(K[fe][0],J))return fe;return-1}function Fc(K,J,fe){var Se=J(K);return Sa(K)?Se:Pe(Se,fe(K))}function _o(K){return K==null?K===void 0?te:Y:ir&&ir in Object(K)?Bu(K):Td(K)}function jc(K){return Ao(K)&&_o(K)==l}function Eo(K,J,fe,Se,Vt){return K===J?!0:K==null||J==null||!Ao(K)&&!Ao(J)?K!==K&&J!==J:Tu(K,J,fe,Se,Eo,Vt)}function Tu(K,J,fe,Se,Vt,ot){var Zt=Sa(K),gr=Sa(J),It=Zt?f:Pi(K),Gt=gr?f:Pi(J);It=It==l?B:It,Gt=Gt==l?B:Gt;var fr=It==B,ln=Gt==B,mr=It==Gt;if(mr&&kc(K)){if(!kc(J))return!1;Zt=!0,fr=!1}if(mr&&!fr)return ot||(ot=new Gr),Zt||Vu(K)?Aa(K,J,fe,Se,Vt,ot):$d(K,J,It,fe,Se,Vt,ot);if(!(fe&i)){var Xt=fr&&je.call(K,"__wrapped__"),Yr=ln&&je.call(J,"__wrapped__");if(Xt||Yr){var ri=Xt?K.value():K,Fn=Yr?J.value():J;return ot||(ot=new Gr),Vt(ri,Fn,fe,Se,ot)}}return mr?(ot||(ot=new Gr),Lu(K,J,fe,Se,Vt,ot)):!1}function Pd(K){if(!Wu(K)||ku(K))return!1;var J=Ia(K)?lt:oe;return J.test(Yi(K))}function Nu(K){return Ao(K)&&Ku(K.length)&&!!A[_o(K)]}function Ru(K){if(!qu(K))return Vr(K);var J=[];for(var fe in Object(K))je.call(K,fe)&&fe!="constructor"&&J.push(fe);return J}function Aa(K,J,fe,Se,Vt,ot){var Zt=fe&i,gr=K.length,It=J.length;if(gr!=It&&!(Zt&&It>gr))return!1;var Gt=ot.get(K);if(Gt&&ot.get(J))return Gt==J;var fr=-1,ln=!0,mr=fe&o?new Mi:void 0;for(ot.set(K,J),ot.set(J,K);++fr<gr;){var Xt=K[fr],Yr=J[fr];if(Se)var ri=Zt?Se(Yr,Xt,fr,J,K,ot):Se(Xt,Yr,fr,K,J,ot);if(ri!==void 0){if(ri)continue;ln=!1;break}if(mr){if(!Ie(J,function(Fn,$i){if(!Ce(mr,$i)&&(Xt===Fn||Vt(Xt,Fn,fe,Se,ot)))return mr.push($i)})){ln=!1;break}}else if(!(Xt===Yr||Vt(Xt,Yr,fe,Se,ot))){ln=!1;break}}return ot.delete(K),ot.delete(J),ln}function $d(K,J,fe,Se,Vt,ot,Zt){switch(fe){case de:if(K.byteLength!=J.byteLength||K.byteOffset!=J.byteOffset)return!1;K=K.buffer,J=J.buffer;case ne:return!(K.byteLength!=J.byteLength||!ot(new nr(K),new nr(J)));case g:case _:case W:return zu(+K,+J);case E:return K.name==J.name&&K.message==J.message;case U:case m:return K==J+"";case k:var gr=Ee;case F:var It=Se&i;if(gr||(gr=Ge),K.size!=J.size&&!It)return!1;var Gt=Zt.get(K);if(Gt)return Gt==J;Se|=o,Zt.set(K,J);var fr=Aa(gr(K),gr(J),Se,Vt,ot,Zt);return Zt.delete(K),fr;case $:if(Ze)return Ze.call(K)==Ze.call(J)}return!1}function Lu(K,J,fe,Se,Vt,ot){var Zt=fe&i,gr=xa(K),It=gr.length,Gt=xa(J),fr=Gt.length;if(It!=fr&&!Zt)return!1;for(var ln=It;ln--;){var mr=gr[ln];if(!(Zt?mr in J:je.call(J,mr)))return!1}var Xt=ot.get(K);if(Xt&&ot.get(J))return Xt==J;var Yr=!0;ot.set(K,J),ot.set(J,K);for(var ri=Zt;++ln<It;){mr=gr[ln];var Fn=K[mr],$i=J[mr];if(Se)var qc=Zt?Se($i,Fn,mr,J,K,ot):Se(Fn,$i,mr,K,J,ot);if(!(qc===void 0?Fn===$i||Vt(Fn,$i,fe,Se,ot):qc)){Yr=!1;break}ri||(ri=mr=="constructor")}if(Yr&&!ri){var xo=K.constructor,Sr=J.constructor;xo!=Sr&&"constructor"in K&&"constructor"in J&&!(typeof xo=="function"&&xo instanceof xo&&typeof Sr=="function"&&Sr instanceof Sr)&&(Yr=!1)}return ot.delete(K),ot.delete(J),Yr}function xa(K){return Fc(K,Ld,Uu)}function Cs(K,J){var fe=K.__data__;return ju(J)?fe[typeof J=="string"?"string":"hash"]:fe.map}function bn(K,J){var fe=Fe(K,J);return Pd(fe)?fe:void 0}function Bu(K){var J=je.call(K,ir),fe=K[ir];try{K[ir]=void 0;var Se=!0}catch{}var Vt=Te.call(K);return Se&&(J?K[ir]=fe:delete K[ir]),Vt}var Uu=St?function(K){return K==null?[]:(K=Object(K),Oe(St(K),function(J){return dt.call(K,J)}))}:Wt,Pi=_o;(Ye&&Pi(new Ye(new ArrayBuffer(1)))!=de||He&&Pi(new He)!=k||Rt&&Pi(Rt.resolve())!=z||Qe&&Pi(new Qe)!=F||Ve&&Pi(new Ve)!=ee)&&(Pi=function(K){var J=_o(K),fe=J==B?K.constructor:void 0,Se=fe?Yi(fe):"";if(Se)switch(Se){case Xe:return de;case et:return k;case Lt:return z;case tt:return F;case Je:return ee}return J});function Fu(K,J){return J=J??c,!!J&&(typeof K=="number"||pe.test(K))&&K>-1&&K%1==0&&K<J}function ju(K){var J=typeof K;return J=="string"||J=="number"||J=="symbol"||J=="boolean"?K!=="__proto__":K===null}function ku(K){return!!$e&&$e in K}function qu(K){var J=K&&K.constructor,fe=typeof J=="function"&&J.prototype||Be;return K===fe}function Td(K){return Te.call(K)}function Yi(K){if(K!=null){try{return Me.call(K)}catch{}try{return K+""}catch{}}return""}function zu(K,J){return K===J||K!==K&&J!==J}var Hu=jc(function(){return arguments}())?jc:function(K){return Ao(K)&&je.call(K,"callee")&&!dt.call(K,"callee")},Sa=Array.isArray;function Nd(K){return K!=null&&Ku(K.length)&&!Ia(K)}var kc=Ot||Kt;function Rd(K,J){return Eo(K,J)}function Ia(K){if(!Wu(K))return!1;var J=_o(K);return J==x||J==I||J==h||J==M}function Ku(K){return typeof K=="number"&&K>-1&&K%1==0&&K<=c}function Wu(K){var J=typeof K;return K!=null&&(J=="object"||J=="function")}function Ao(K){return K!=null&&typeof K=="object"}var Vu=le?ze(le):Nu;function Ld(K){return Nd(K)?$u(K):Ru(K)}function Wt(){return[]}function Kt(){return!1}t.exports=Rd})(t0,t0.exports);var l9=t0.exports;function u9(t,e){return e=e||{},new Promise(function(r,n){var i=new XMLHttpRequest,o=[],c=[],l={},f=function(){return{ok:(i.status/100|0)==2,statusText:i.statusText,status:i.status,url:i.responseURL,text:function(){return Promise.resolve(i.responseText)},json:function(){return Promise.resolve(i.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([i.response]))},clone:f,headers:{keys:function(){return o},entries:function(){return c},get:function(g){return l[g.toLowerCase()]},has:function(g){return g.toLowerCase()in l}}}};for(var h in i.open(e.method||"get",t,!0),i.onload=function(){i.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(g,_,E){o.push(_=_.toLowerCase()),c.push([_,E]),l[_]=l[_]?l[_]+","+E:E}),r(f())},i.onerror=n,i.withCredentials=e.credentials=="include",e.headers)i.setRequestHeader(h,e.headers[h]);i.send(e.body||null)})}var h9=Object.freeze({__proto__:null,default:u9}),yv=il(h9),f9=self.fetch||(self.fetch=yv.default||yv),d9=Object.defineProperty,bv=Object.getOwnPropertySymbols,p9=Object.prototype.hasOwnProperty,g9=Object.prototype.propertyIsEnumerable,_v=(t,e,r)=>e in t?d9(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Kr=(t,e)=>{for(var r in e||(e={}))p9.call(e,r)&&_v(t,r,e[r]);if(bv)for(var r of bv(e))g9.call(e,r)&&_v(t,r,e[r]);return t};function m9(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var o=t.charAt(i),c=o.charCodeAt(0);if(r[c]!==255)throw new TypeError(o+" is ambiguous");r[c]=i}var l=t.length,f=t.charAt(0),h=Math.log(l)/Math.log(256),g=Math.log(256)/Math.log(l);function _(I){if(I instanceof Uint8Array||(ArrayBuffer.isView(I)?I=new Uint8Array(I.buffer,I.byteOffset,I.byteLength):Array.isArray(I)&&(I=Uint8Array.from(I))),!(I instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(I.length===0)return"";for(var k=0,W=0,Y=0,B=I.length;Y!==B&&I[Y]===0;)Y++,k++;for(var z=(B-Y)*g+1>>>0,M=new Uint8Array(z);Y!==B;){for(var U=I[Y],F=0,m=z-1;(U!==0||F<W)&&m!==-1;m--,F++)U+=256*M[m]>>>0,M[m]=U%l>>>0,U=U/l>>>0;if(U!==0)throw new Error("Non-zero carry");W=F,Y++}for(var $=z-W;$!==z&&M[$]===0;)$++;for(var te=f.repeat(k);$<z;++$)te+=t.charAt(M[$]);return te}function E(I){if(typeof I!="string")throw new TypeError("Expected String");if(I.length===0)return new Uint8Array;var k=0;if(I[k]!==" "){for(var W=0,Y=0;I[k]===f;)W++,k++;for(var B=(I.length-k)*h+1>>>0,z=new Uint8Array(B);I[k];){var M=r[I.charCodeAt(k)];if(M===255)return;for(var U=0,F=B-1;(M!==0||U<Y)&&F!==-1;F--,U++)M+=l*z[F]>>>0,z[F]=M%256>>>0,M=M/256>>>0;if(M!==0)throw new Error("Non-zero carry");Y=U,k++}if(I[k]!==" "){for(var m=B-Y;m!==B&&z[m]===0;)m++;for(var $=new Uint8Array(W+(B-m)),te=W;m!==B;)$[te++]=z[m++];return $}}}function x(I){var k=E(I);if(k)return k;throw new Error(`Non-${e} character`)}return{encode:_,decodeUnsafe:E,decode:x}}var v9=m9,w9=v9;const Ev=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},y9=t=>new TextEncoder().encode(t),b9=t=>new TextDecoder().decode(t);class _9{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class E9{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Av(this,e)}}class A9{constructor(e){this.decoders=e}or(e){return Av(this,e)}decode(e){const r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Av=(t,e)=>new A9(Kr(Kr({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class x9{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new _9(e,r,n),this.decoder=new E9(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Yl=({name:t,prefix:e,encode:r,decode:n})=>new x9(t,e,r,n),mc=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=w9(r,e);return Yl({prefix:t,name:e,encode:n,decode:o=>Ev(i(o))})},S9=(t,e,r,n)=>{const i={};for(let g=0;g<e.length;++g)i[e[g]]=g;let o=t.length;for(;t[o-1]==="=";)--o;const c=new Uint8Array(o*r/8|0);let l=0,f=0,h=0;for(let g=0;g<o;++g){const _=i[t[g]];if(_===void 0)throw new SyntaxError(`Non-${n} character`);f=f<<r|_,l+=r,l>=8&&(l-=8,c[h++]=255&f>>l)}if(l>=r||255&f<<8-l)throw new SyntaxError("Unexpected end of data");return c},I9=(t,e,r)=>{const n=e[e.length-1]==="=",i=(1<<r)-1;let o="",c=0,l=0;for(let f=0;f<t.length;++f)for(l=l<<8|t[f],c+=8;c>r;)c-=r,o+=e[i&l>>c];if(c&&(o+=e[i&l<<r-c]),n)for(;o.length*r&7;)o+="=";return o},$r=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>Yl({prefix:e,name:t,encode(i){return I9(i,n,r)},decode(i){return S9(i,n,r,t)}}),D9=Yl({prefix:"\0",name:"identity",encode:t=>b9(t),decode:t=>y9(t)});var C9=Object.freeze({__proto__:null,identity:D9});const O9=$r({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var M9=Object.freeze({__proto__:null,base2:O9});const P9=$r({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var $9=Object.freeze({__proto__:null,base8:P9});const T9=mc({prefix:"9",name:"base10",alphabet:"0123456789"});var N9=Object.freeze({__proto__:null,base10:T9});const R9=$r({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),L9=$r({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var B9=Object.freeze({__proto__:null,base16:R9,base16upper:L9});const U9=$r({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),F9=$r({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),j9=$r({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),k9=$r({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),q9=$r({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),z9=$r({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),H9=$r({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),K9=$r({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),W9=$r({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var V9=Object.freeze({__proto__:null,base32:U9,base32upper:F9,base32pad:j9,base32padupper:k9,base32hex:q9,base32hexupper:z9,base32hexpad:H9,base32hexpadupper:K9,base32z:W9});const G9=mc({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Y9=mc({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Q9=Object.freeze({__proto__:null,base36:G9,base36upper:Y9});const J9=mc({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Z9=mc({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var X9=Object.freeze({__proto__:null,base58btc:J9,base58flickr:Z9});const eS=$r({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),tS=$r({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),rS=$r({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),nS=$r({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var iS=Object.freeze({__proto__:null,base64:eS,base64pad:tS,base64url:rS,base64urlpad:nS});const xv=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),sS=xv.reduce((t,e,r)=>(t[r]=e,t),[]),oS=xv.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function aS(t){return t.reduce((e,r)=>(e+=sS[r],e),"")}function cS(t){const e=[];for(const r of t){const n=oS[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const lS=Yl({prefix:"\u{1F680}",name:"base256emoji",encode:aS,decode:cS});var uS=Object.freeze({__proto__:null,base256emoji:lS}),hS=Iv,Sv=128,fS=127,dS=~fS,pS=Math.pow(2,31);function Iv(t,e,r){e=e||[],r=r||0;for(var n=r;t>=pS;)e[r++]=t&255|Sv,t/=128;for(;t&dS;)e[r++]=t&255|Sv,t>>>=7;return e[r]=t|0,Iv.bytes=r-n+1,e}var gS=r0,mS=128,Dv=127;function r0(t,n){var r=0,n=n||0,i=0,o=n,c,l=t.length;do{if(o>=l)throw r0.bytes=0,new RangeError("Could not decode varint");c=t[o++],r+=i<28?(c&Dv)<<i:(c&Dv)*Math.pow(2,i),i+=7}while(c>=mS);return r0.bytes=o-n,r}var vS=Math.pow(2,7),wS=Math.pow(2,14),yS=Math.pow(2,21),bS=Math.pow(2,28),_S=Math.pow(2,35),ES=Math.pow(2,42),AS=Math.pow(2,49),xS=Math.pow(2,56),SS=Math.pow(2,63),IS=function(t){return t<vS?1:t<wS?2:t<yS?3:t<bS?4:t<_S?5:t<ES?6:t<AS?7:t<xS?8:t<SS?9:10},DS={encode:hS,decode:gS,encodingLength:IS},Cv=DS;const Ov=(t,e,r=0)=>(Cv.encode(t,e,r),e),Mv=t=>Cv.encodingLength(t),n0=(t,e)=>{const r=e.byteLength,n=Mv(t),i=n+Mv(r),o=new Uint8Array(i+r);return Ov(t,o,0),Ov(r,o,n),o.set(e,i),new CS(t,r,e,o)};class CS{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const Pv=({name:t,code:e,encode:r})=>new OS(t,e,r);class OS{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?n0(this.code,r):r.then(n=>n0(this.code,n))}else throw Error("Unknown type, must be binary type")}}const $v=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),MS=Pv({name:"sha2-256",code:18,encode:$v("SHA-256")}),PS=Pv({name:"sha2-512",code:19,encode:$v("SHA-512")});var $S=Object.freeze({__proto__:null,sha256:MS,sha512:PS});const Tv=0,TS="identity",Nv=Ev;var NS=Object.freeze({__proto__:null,identity:{code:Tv,name:TS,encode:Nv,digest:t=>n0(Tv,Nv(t))}});new TextEncoder,new TextDecoder;const Rv=Kr(Kr(Kr(Kr(Kr(Kr(Kr(Kr(Kr(Kr({},C9),M9),$9),N9),B9),V9),Q9),X9),iS),uS);Kr(Kr({},$S),NS);function RS(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function Lv(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const Bv=Lv("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),i0=Lv("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=RS(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),LS=Kr({utf8:Bv,"utf-8":Bv,hex:Rv.base16,latin1:i0,ascii:i0,binary:i0},Rv);function BS(t,e="utf8"){const r=LS[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t,"utf8"):r.decoder.decode(`${r.prefix}${t}`)}const Uv="wc",US=2,s0="core",hs=`${Uv}@2:${s0}:`,FS={name:s0,logger:"error"},jS={database:":memory:"},kS="crypto",Fv="client_ed25519_seed",qS=ye.ONE_DAY,zS="keychain",HS="0.3",KS="messages",WS="0.3",VS=ye.SIX_HOURS,GS="publisher",jv="irn",YS="error",kv="wss://relay.walletconnect.com",qv="wss://relay.walletconnect.org",QS="relayer",on={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},JS="_subscription",Pn={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},ZS=ye.ONE_SECOND,XS="2.13.3",eI=1e4,tI="0.3",rI="WALLETCONNECT_CLIENT_ID",Ei={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},nI="subscription",iI="0.3",sI=ye.FIVE_SECONDS*1e3,oI="pairing",aI="0.3",vc={wc_pairingDelete:{req:{ttl:ye.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:ye.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:ye.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:ye.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:ye.ONE_DAY,prompt:!1,tag:0},res:{ttl:ye.ONE_DAY,prompt:!1,tag:0}}},ra={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},ei={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},cI="history",lI="0.3",uI="expirer",$n={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},hI="0.3",o0="verify-api",na="https://verify.walletconnect.com",a0="https://verify.walletconnect.org",fI=[na,a0],dI="echo",pI="https://echo.walletconnect.com";class gI{constructor(e,r){this.core=e,this.logger=r,this.keychain=new Map,this.name=zS,this.version=HS,this.initialized=!1,this.storagePrefix=hs,this.init=async()=>{if(!this.initialized){const n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}},this.has=n=>(this.isInitialized(),this.keychain.has(n)),this.set=async(n,i)=>{this.isInitialized(),this.keychain.set(n,i),await this.persist()},this.get=n=>{this.isInitialized();const i=this.keychain.get(n);if(typeof i>"u"){const{message:o}=me("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(o)}return i},this.del=async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()},this.core=e,this.logger=sn(r,this.name)}get context(){return nn(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,eg(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?tg(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=me("NOT_INITIALIZED",this.name);throw new Error(e)}}}class mI{constructor(e,r,n){this.core=e,this.logger=r,this.name=kS,this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=i=>(this.isInitialized(),this.keychain.has(i)),this.getClientId=async()=>{this.isInitialized();const i=await this.getClientSeed(),o=rv(i);return tv(o.publicKey)},this.generateKeyPair=()=>{this.isInitialized();const i=FE();return this.setPrivateKey(i.publicKey,i.privateKey)},this.signJWT=async i=>{this.isInitialized();const o=await this.getClientSeed(),c=rv(o),l=Pf();return await vx(l,i,qS,c)},this.generateSharedKey=(i,o,c)=>{this.isInitialized();const l=this.getPrivateKey(i),f=jE(l,o);return this.setSymKey(f,c)},this.setSymKey=async(i,o)=>{this.isInitialized();const c=o||Tl(i);return await this.keychain.set(c,i),c},this.deleteKeyPair=async i=>{this.isInitialized(),await this.keychain.del(i)},this.deleteSymKey=async i=>{this.isInitialized(),await this.keychain.del(i)},this.encode=async(i,o,c)=>{this.isInitialized();const l=ym(c),f=ki(o);if(bm(l)){const E=l.senderPublicKey,x=l.receiverPublicKey;i=await this.generateSharedKey(E,x)}const h=this.getSymKey(i),{type:g,senderPublicKey:_}=l;return qE({type:g,symKey:h,message:f,senderPublicKey:_})},this.decode=async(i,o,c)=>{this.isInitialized();const l=KE(o,c);if(bm(l)){const f=l.receiverPublicKey,h=l.senderPublicKey;i=await this.generateSharedKey(f,h)}try{const f=this.getSymKey(i),h=zE({symKey:f,encoded:o});return lc(h)}catch(f){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(f)}},this.getPayloadType=i=>{const o=Nl(i);return nc(o.type)},this.getPayloadSenderPublicKey=i=>{const o=Nl(i);return o.senderPublicKey?bx(o.senderPublicKey,zr):void 0},this.core=e,this.logger=sn(r,this.name),this.keychain=n||new gI(this.core,this.logger)}get context(){return nn(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(Fv)}catch{e=Pf(),await this.keychain.set(Fv,e)}return BS(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=me("NOT_INITIALIZED",this.name);throw new Error(e)}}}class vI extends V7{constructor(e,r){super(e,r),this.logger=e,this.core=r,this.messages=new Map,this.name=KS,this.version=WS,this.initialized=!1,this.storagePrefix=hs,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}},this.set=async(n,i)=>{this.isInitialized();const o=Ws(i);let c=this.messages.get(n);return typeof c>"u"&&(c={}),typeof c[o]<"u"||(c[o]=i,this.messages.set(n,c),await this.persist()),o},this.get=n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i},this.has=(n,i)=>{this.isInitialized();const o=this.get(n),c=Ws(i);return typeof o[c]<"u"},this.del=async n=>{this.isInitialized(),this.messages.delete(n),await this.persist()},this.logger=sn(e,this.name),this.core=r}get context(){return nn(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,eg(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?tg(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=me("NOT_INITIALIZED",this.name);throw new Error(e)}}}class wI extends G7{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.events=new Dr.exports.EventEmitter,this.name=GS,this.queue=new Map,this.publishTimeout=ye.toMiliseconds(ye.ONE_MINUTE),this.failedPublishTimeout=ye.toMiliseconds(ye.ONE_SECOND),this.needsTransportRestart=!1,this.publish=async(n,i,o)=>{var c;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:o}});const l=o?.ttl||VS,f=$f(o),h=o?.prompt||!1,g=o?.tag||0,_=o?.id||Ys().toString(),E={topic:n,message:i,opts:{ttl:l,relay:f,prompt:h,tag:g,id:_}},x=`Failed to publish payload, please try again. id:${_} tag:${g}`,I=Date.now();let k,W=1;try{for(;k===void 0;){if(Date.now()-I>this.publishTimeout)throw new Error(x);this.logger.trace({id:_,attempts:W},`publisher.publish - attempt ${W}`),k=await await jo(this.rpcPublish(n,i,l,f,h,g,_).catch(Y=>this.logger.warn(Y)),this.publishTimeout,x),W++,k||await new Promise(Y=>setTimeout(Y,this.failedPublishTimeout))}this.relayer.events.emit(on.publish,E),this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{id:_,topic:n,message:i,opts:o}})}catch(Y){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(Y),(c=o?.internal)!=null&&c.throwOnFailedPublish)throw Y;this.queue.set(_,E)}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.relayer=e,this.logger=sn(r,this.name),this.registerEventListeners()}get context(){return nn(this.logger)}rpcPublish(e,r,n,i,o,c,l){var f,h,g,_;const E={method:ic(i.protocol).publish,params:{topic:e,message:r,ttl:n,prompt:o,tag:c},id:l};return Hr((f=E.params)==null?void 0:f.prompt)&&((h=E.params)==null||delete h.prompt),Hr((g=E.params)==null?void 0:g.tag)&&((_=E.params)==null||delete _.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:E}),this.relayer.request(E)}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async e=>{const{topic:r,message:n,opts:i}=e;await this.publish(r,n,i)})}registerEventListeners(){this.relayer.core.heartbeat.on(uc.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(on.connection_stalled);return}this.checkQueue()}),this.relayer.on(on.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}class yI{constructor(){this.map=new Map,this.set=(e,r)=>{const n=this.get(e);this.exists(e,r)||this.map.set(e,[...n,r])},this.get=e=>this.map.get(e)||[],this.exists=(e,r)=>this.get(e).includes(r),this.delete=(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const n=this.get(e);if(!this.exists(e,r))return;const i=n.filter(o=>o!==r);if(!i.length){this.map.delete(e);return}this.map.set(e,i)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}}var bI=Object.defineProperty,_I=Object.defineProperties,EI=Object.getOwnPropertyDescriptors,zv=Object.getOwnPropertySymbols,AI=Object.prototype.hasOwnProperty,xI=Object.prototype.propertyIsEnumerable,Hv=(t,e,r)=>e in t?bI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,wc=(t,e)=>{for(var r in e||(e={}))AI.call(e,r)&&Hv(t,r,e[r]);if(zv)for(var r of zv(e))xI.call(e,r)&&Hv(t,r,e[r]);return t},c0=(t,e)=>_I(t,EI(e));class SI extends J7{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.subscriptions=new Map,this.topicMap=new yI,this.events=new Dr.exports.EventEmitter,this.name=nI,this.version=iI,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=hs,this.subscribeTimeout=ye.toMiliseconds(ye.ONE_MINUTE),this.restartInProgress=!1,this.batchSubscribeTopicsLimit=500,this.pendingBatchMessages=[],this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),this.clientId=await this.relayer.core.crypto.getClientId())},this.subscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}});try{const o=$f(i),c={topic:n,relay:o};this.pending.set(n,c);const l=await this.rpcSubscribe(n,o);return typeof l=="string"&&(this.onSubscribe(l,c),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}})),l}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}},this.unsubscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(n,i.id,i):await this.unsubscribeByTopic(n,i)},this.isSubscribed=async n=>{if(this.topics.includes(n))return!0;const i=`${this.pendingSubscriptionWatchLabel}_${n}`;return await new Promise((o,c)=>{const l=new ye.Watch;l.start(i);const f=setInterval(()=>{!this.pending.has(n)&&this.topics.includes(n)&&(clearInterval(f),l.stop(i),o(!0)),l.elapsed(i)>=sI&&(clearInterval(f),l.stop(i),c(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1)},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.start=async()=>{await this.onConnect()},this.stop=async()=>{await this.onDisconnect()},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=sn(r,this.name),this.clientId=""}get context(){return nn(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}hasSubscription(e,r){let n=!1;try{n=this.getSubscription(e).topic===r}catch{}return n}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){const n=this.topicMap.get(e);await Promise.all(n.map(async i=>await this.unsubscribeById(e,i,r)))}async unsubscribeById(e,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}});try{const i=$f(n);await this.rpcUnsubscribe(e,r,i);const o=Ut("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,o),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,r){const n={method:ic(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{return await await jo(this.relayer.request(n).catch(i=>this.logger.warn(i)),this.subscribeTimeout)?Ws(e+this.clientId):null}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(on.connection_stalled)}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,n={method:ic(r.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{return await await jo(this.relayer.request(n).catch(i=>this.logger.warn(i)),this.subscribeTimeout)}catch{this.relayer.events.emit(on.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,n={method:ic(r.protocol).batchFetchMessages,params:{topics:e.map(o=>o.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});let i;try{i=await await jo(this.relayer.request(n).catch(o=>this.logger.warn(o)),this.subscribeTimeout)}catch{this.relayer.events.emit(on.connection_stalled)}return i}rpcUnsubscribe(e,r,n){const i={method:ic(n.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,r){this.setSubscription(e,c0(wc({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,wc({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,n){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,n),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r)}addSubscription(e,r){this.subscriptions.set(e,wc({},r)),this.topicMap.set(r.topic,e),this.events.emit(Ei.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const r=this.subscriptions.get(e);if(!r){const{message:n}=me("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(Ei.deleted,c0(wc({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Ei.sync)}async reset(){if(this.cached.length){const e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<e;r++){const n=this.cached.splice(0,this.batchSubscribeTopicsLimit);await this.batchFetchMessages(n),await this.batchSubscribe(n)}}this.events.emit(Ei.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:r}=me("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){if(!e.length)return;const r=await this.rpcBatchSubscribe(e);wi(r)&&this.onBatchSubscribe(r.map((n,i)=>c0(wc({},e[i]),{id:n})))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const r=await this.rpcBatchFetchMessages(e);r&&r.messages&&(this.pendingBatchMessages=this.pendingBatchMessages.concat(r.messages))}async onConnect(){await this.restart(),this.onEnable()}onDisconnect(){this.onDisable()}async checkPending(){if(!this.initialized||!this.relayer.connected)return;const e=[];this.pending.forEach(r=>{e.push(r)}),await this.batchSubscribe(e),this.pendingBatchMessages.length&&(await this.relayer.handleBatchMessageEvents(this.pendingBatchMessages),this.pendingBatchMessages=[])}registerEventListeners(){this.relayer.core.heartbeat.on(uc.pulse,async()=>{await this.checkPending()}),this.events.on(Ei.created,async e=>{const r=Ei.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()}),this.events.on(Ei.deleted,async e=>{const r=Ei.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=me("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){this.restartInProgress&&await new Promise(e=>{const r=setInterval(()=>{this.restartInProgress||(clearInterval(r),e())},this.pollingInterval)})}}var II=Object.defineProperty,Kv=Object.getOwnPropertySymbols,DI=Object.prototype.hasOwnProperty,CI=Object.prototype.propertyIsEnumerable,Wv=(t,e,r)=>e in t?II(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,OI=(t,e)=>{for(var r in e||(e={}))DI.call(e,r)&&Wv(t,r,e[r]);if(Kv)for(var r of Kv(e))CI.call(e,r)&&Wv(t,r,e[r]);return t};class MI extends Y7{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new Dr.exports.EventEmitter,this.name=QS,this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.connectionStatusPollingInterval=20,this.staleConnectionErrors=["socket hang up","stalled","interrupted"],this.hasExperiencedNetworkDisruption=!1,this.requestsInFlight=new Map,this.heartBeatTimeout=ye.toMiliseconds(ye.THIRTY_SECONDS+ye.ONE_SECOND),this.request=async r=>{var n,i;this.logger.debug("Publishing Request Payload");const o=r.id||Ys().toString();await this.toEstablishConnection();try{const c=this.provider.request(r);this.requestsInFlight.set(o,{promise:c,request:r}),this.logger.trace({id:o,method:r.method,topic:(n=r.params)==null?void 0:n.topic},"relayer.request - attempt to publish...");const l=await new Promise(async(f,h)=>{const g=()=>{h(new Error(`relayer.request - publish interrupted, id: ${o}`))};this.provider.on(Pn.disconnect,g);const _=await c;this.provider.off(Pn.disconnect,g),f(_)});return this.logger.trace({id:o,method:r.method,topic:(i=r.params)==null?void 0:i.topic},"relayer.request - published"),l}catch(c){throw this.logger.debug(`Failed to Publish Request: ${o}`),c}finally{this.requestsInFlight.delete(o)}},this.resetPingTimeout=()=>{if(Wa())try{clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,n,i;(i=(n=(r=this.provider)==null?void 0:r.connection)==null?void 0:n.socket)==null||i.terminate()},this.heartBeatTimeout)}catch(r){this.logger.warn(r)}},this.onPayloadHandler=r=>{this.onProviderPayload(r),this.resetPingTimeout()},this.onConnectHandler=()=>{this.startPingTimeout(),this.events.emit(on.connect)},this.onDisconnectHandler=()=>{this.onProviderDisconnect()},this.onProviderErrorHandler=r=>{this.logger.error(r),this.events.emit(on.error,r),this.logger.info("Fatal socket error received, closing transport"),this.transportClose()},this.registerProviderListeners=()=>{this.provider.on(Pn.payload,this.onPayloadHandler),this.provider.on(Pn.connect,this.onConnectHandler),this.provider.on(Pn.disconnect,this.onDisconnectHandler),this.provider.on(Pn.error,this.onProviderErrorHandler)},this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?sn(e.logger,this.name):yi(Hl({level:e.logger||YS})),this.messages=new vI(this.logger,e.core),this.subscriber=new SI(this,this.logger),this.publisher=new wI(this,this.logger),this.relayUrl=e?.relayUrl||kv,this.projectId=e.projectId,this.bundleId=C8(),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),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 ${qv}...`),await this.restartTransport(qv)}this.initialized=!0,setTimeout(async()=>{this.subscriber.topics.length===0&&this.subscriber.pending.size===0&&(this.logger.info("No topics subscribed to after init, closing transport"),await this.transportClose(),this.transportExplicitlyClosed=!1)},eI)}get context(){return nn(this.logger)}get connected(){var e,r,n;return((n=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===1}get connecting(){var e,r,n;return((n=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===0}async publish(e,r,n){this.isInitialized(),await this.publisher.publish(e,r,n),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now()})}async subscribe(e,r){var n;this.isInitialized();let i=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",o;const c=l=>{l.topic===e&&(this.subscriber.off(Ei.created,c),o())};return await Promise.all([new Promise(l=>{o=l,this.subscriber.on(Ei.created,c)}),new Promise(async l=>{i=await this.subscriber.subscribe(e,r)||i,l()})]),i}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportDisconnect(){if(!this.hasExperiencedNetworkDisruption&&this.connected&&this.requestsInFlight.size>0)try{await Promise.all(Array.from(this.requestsInFlight.values()).map(e=>e.promise))}catch(e){this.logger.warn(e)}this.hasExperiencedNetworkDisruption||this.connected?await jo(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),await this.createProvider(),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;try{await new Promise(async(r,n)=>{const i=()=>{this.provider.off(Pn.disconnect,i),n(new Error("Connection interrupted while trying to subscribe"))};this.provider.on(Pn.disconnect,i),await jo(this.provider.connect(),ye.toMiliseconds(ye.ONE_MINUTE),`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{n(o)}),await this.subscriber.start(),this.hasExperiencedNetworkDisruption=!1,r()})}catch(r){this.logger.error(r);const n=r;if(this.hasExperiencedNetworkDisruption=!0,!this.isConnectionStalled(n.message))throw r}finally{this.connectionAttemptInProgress=!1}}async restartTransport(e){this.connectionAttemptInProgress||(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await $m())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(e?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const r=e.sort((n,i)=>n.publishedAt-i.publishedAt);this.logger.trace(`Batch of ${r.length} message events sorted`);for(const n of r)try{await this.onMessageEvent(n)}catch(i){this.logger.warn(i)}this.logger.trace(`Batch of ${r.length} message events processed`)}startPingTimeout(){var e,r,n,i,o;if(Wa())try{(r=(e=this.provider)==null?void 0:e.connection)!=null&&r.socket&&((o=(i=(n=this.provider)==null?void 0:n.connection)==null?void 0:i.socket)==null||o.once("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(c){this.logger.warn(c)}}isConnectionStalled(e){return this.staleConnectionErrors.some(r=>e.includes(r))}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Hi(new c9(N8({sdkVersion:XS,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId}))),this.registerProviderListeners()}async recordMessageEvent(e){const{topic:r,message:n}=e;await this.messages.set(r,n)}async shouldIgnoreMessageEvent(e){const{topic:r,message:n}=e;if(!n||n.length===0)return this.logger.debug(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isSubscribed(r))return this.logger.debug(`Ignoring message for non-subscribed topic ${r}`),!0;const i=this.messages.has(r,n);return i&&this.logger.debug(`Ignoring duplicate message: ${n}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),e0(e)){if(!e.method.endsWith(JS))return;const r=e.params,{topic:n,message:i,publishedAt:o}=r.data,c={topic:n,message:i,publishedAt:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(OI({type:"event",event:r.id},c)),this.events.emit(r.id,c),await this.acknowledgePayload(e),await this.onMessageEvent(c)}else Gl(e)&&this.events.emit(on.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(on.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const r=Wl(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(Pn.payload,this.onPayloadHandler),this.provider.off(Pn.connect,this.onConnectHandler),this.provider.off(Pn.disconnect,this.onDisconnectHandler),this.provider.off(Pn.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await $m();RA(async r=>{e!==r&&(e=r,r?await this.restartTransport().catch(n=>this.logger.error(n)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))})}async onProviderDisconnect(){await this.subscriber.stop(),this.requestsInFlight.clear(),clearTimeout(this.pingTimeout),this.events.emit(on.disconnect),this.connectionAttemptInProgress=!1,!this.transportExplicitlyClosed&&setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e))},ye.toMiliseconds(ZS))}isInitialized(){if(!this.initialized){const{message:e}=me("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&(this.connectionAttemptInProgress&&await new Promise(e=>{const r=setInterval(()=>{this.connected&&(clearInterval(r),e())},this.connectionStatusPollingInterval)}),await this.transportOpen())}}var PI=Object.defineProperty,Vv=Object.getOwnPropertySymbols,$I=Object.prototype.hasOwnProperty,TI=Object.prototype.propertyIsEnumerable,Gv=(t,e,r)=>e in t?PI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Yv=(t,e)=>{for(var r in e||(e={}))$I.call(e,r)&&Gv(t,r,e[r]);if(Vv)for(var r of Vv(e))TI.call(e,r)&&Gv(t,r,e[r]);return t};class Qs extends Q7{constructor(e,r,n,i=hs,o=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,this.map=new Map,this.version=tI,this.cached=[],this.initialized=!1,this.storagePrefix=hs,this.recentlyDeleted=[],this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(c=>{this.getKey&&c!==null&&!Hr(c)?this.map.set(this.getKey(c),c):fA(c)?this.map.set(c.id,c):dA(c)&&this.map.set(c.topic,c)}),this.cached=[],this.initialized=!0)},this.set=async(c,l)=>{this.isInitialized(),this.map.has(c)?await this.update(c,l):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:c,value:l}),this.map.set(c,l),await this.persist())},this.get=c=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:c}),this.getData(c)),this.getAll=c=>(this.isInitialized(),c?this.values.filter(l=>Object.keys(c).every(f=>l9(l[f],c[f]))):this.values),this.update=async(c,l)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:c,update:l});const f=Yv(Yv({},this.getData(c)),l);this.map.set(c,f),await this.persist()},this.delete=async(c,l)=>{this.isInitialized(),this.map.has(c)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:c,reason:l}),this.map.delete(c),this.addToRecentlyDeleted(c),await this.persist())},this.logger=sn(r,this.name),this.storagePrefix=i,this.getKey=o}get context(){return nn(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const r=this.map.get(e);if(!r){if(this.recentlyDeleted.includes(e)){const{message:i}=me("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}const{message:n}=me("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:r}=me("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=me("NOT_INITIALIZED",this.name);throw new Error(e)}}}class NI{constructor(e,r){this.core=e,this.logger=r,this.name=oI,this.version=aI,this.events=new Dr.exports,this.initialized=!1,this.storagePrefix=hs,this.ignoredPayloadTypes=[ji],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=({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]},this.create=async n=>{this.isInitialized();const i=Pf(),o=await this.core.crypto.setSymKey(i),c=Or(ye.FIVE_MINUTES),l={protocol:jv},f={topic:o,expiry:c,relay:l,active:!1},h=rA({protocol:this.core.protocol,version:this.core.version,topic:o,symKey:i,relay:l,expiryTimestamp:c,methods:n?.methods});return this.core.expirer.set(o,c),await this.pairings.set(o,f),await this.core.relayer.subscribe(o),{topic:o,uri:h}},this.pair=async n=>{this.isInitialized(),this.isValidPair(n);const{topic:i,symKey:o,relay:c,expiryTimestamp:l,methods:f}=xm(n.uri);let h;if(this.pairings.keys.includes(i)&&(h=this.pairings.get(i),h.active))throw new Error(`Pairing already exists: ${i}. Please try again with a new connection URI.`);const g=l||Or(ye.FIVE_MINUTES),_={topic:i,relay:c,expiry:g,active:!1,methods:f};return this.core.expirer.set(i,g),await this.pairings.set(i,_),n.activatePairing&&await this.activate({topic:i}),this.events.emit(ra.create,_),this.core.crypto.keychain.has(i)||await this.core.crypto.setSymKey(o,i),await this.core.relayer.subscribe(i,{relay:c}),_},this.activate=async({topic:n})=>{this.isInitialized();const i=Or(ye.THIRTY_DAYS);this.core.expirer.set(n,i),await this.pairings.update(n,{active:!0,expiry:i})},this.ping=async n=>{this.isInitialized(),await this.isValidPing(n);const{topic:i}=n;if(this.pairings.keys.includes(i)){const o=await this.sendRequest(i,"wc_pairingPing",{}),{done:c,resolve:l,reject:f}=qs();this.events.once(wt("pairing_ping",o),({error:h})=>{h?f(h):l()}),await c()}},this.updateExpiry=async({topic:n,expiry:i})=>{this.isInitialized(),await this.pairings.update(n,{expiry:i})},this.updateMetadata=async({topic:n,metadata:i})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:i})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async n=>{this.isInitialized(),await this.isValidDisconnect(n);const{topic:i}=n;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",Ut("USER_DISCONNECTED")),await this.deletePairing(i))},this.sendRequest=async(n,i,o)=>{const c=ta(i,o),l=await this.core.crypto.encode(n,c),f=vc[i].req;return this.core.history.set(n,c),this.core.relayer.publish(n,l,f),c.id},this.sendResult=async(n,i,o)=>{const c=Wl(n,o),l=await this.core.crypto.encode(i,c),f=await this.core.history.get(i,n),h=vc[f.request.method].res;await this.core.relayer.publish(i,l,h),await this.core.history.resolve(c)},this.sendError=async(n,i,o)=>{const c=Vl(n,o),l=await this.core.crypto.encode(i,c),f=await this.core.history.get(i,n),h=vc[f.request.method]?vc[f.request.method].res:vc.unregistered_method.res;await this.core.relayer.publish(i,l,h),await this.core.history.resolve(c)},this.deletePairing=async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,Ut("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])},this.cleanup=async()=>{const n=this.pairings.getAll().filter(i=>os(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))},this.onRelayEventRequest=n=>{const{topic:i,payload:o}=n;switch(o.method){case"wc_pairingPing":return this.onPairingPingRequest(i,o);case"wc_pairingDelete":return this.onPairingDeleteRequest(i,o);default:return this.onUnknownRpcMethodRequest(i,o)}},this.onRelayEventResponse=async n=>{const{topic:i,payload:o}=n,c=(await this.core.history.get(i,o.id)).request.method;switch(c){case"wc_pairingPing":return this.onPairingPingResponse(i,o);default:return this.onUnknownRpcMethodResponse(c)}},this.onPairingPingRequest=async(n,i)=>{const{id:o}=i;try{this.isValidPing({topic:n}),await this.sendResult(o,n,!0),this.events.emit(ra.ping,{id:o,topic:n})}catch(c){await this.sendError(o,n,c),this.logger.error(c)}},this.onPairingPingResponse=(n,i)=>{const{id:o}=i;setTimeout(()=>{_i(i)?this.events.emit(wt("pairing_ping",o),{}):Mn(i)&&this.events.emit(wt("pairing_ping",o),{error:i.error})},500)},this.onPairingDeleteRequest=async(n,i)=>{const{id:o}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(ra.delete,{id:o,topic:n})}catch(c){await this.sendError(o,n,c),this.logger.error(c)}},this.onUnknownRpcMethodRequest=async(n,i)=>{const{id:o,method:c}=i;try{if(this.registeredMethods.includes(c))return;const l=Ut("WC_METHOD_UNSUPPORTED",c);await this.sendError(o,n,l),this.logger.error(l)}catch(l){await this.sendError(o,n,l),this.logger.error(l)}},this.onUnknownRpcMethodResponse=n=>{this.registeredMethods.includes(n)||this.logger.error(Ut("WC_METHOD_UNSUPPORTED",n))},this.isValidPair=n=>{var i;if(!tn(n)){const{message:c}=me("MISSING_OR_INVALID",`pair() params: ${n}`);throw new Error(c)}if(!hA(n.uri)){const{message:c}=me("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw new Error(c)}const o=xm(n.uri);if(!((i=o?.relay)!=null&&i.protocol)){const{message:c}=me("MISSING_OR_INVALID","pair() uri#relay-protocol");throw new Error(c)}if(!(o!=null&&o.symKey)){const{message:c}=me("MISSING_OR_INVALID","pair() uri#symKey");throw new Error(c)}if(o!=null&&o.expiryTimestamp&&ye.toMiliseconds(o?.expiryTimestamp)<Date.now()){const{message:c}=me("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(c)}},this.isValidPing=async n=>{if(!tn(n)){const{message:o}=me("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(o)}const{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidDisconnect=async n=>{if(!tn(n)){const{message:o}=me("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(o)}const{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidPairingTopic=async n=>{if(!ur(n,!1)){const{message:i}=me("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){const{message:i}=me("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(os(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:i}=me("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}},this.core=e,this.logger=sn(r,this.name),this.pairings=new Qs(this.core,this.logger,this.name,this.storagePrefix)}get context(){return nn(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=me("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(on.message,async e=>{const{topic:r,message:n}=e;if(!this.pairings.keys.includes(r)||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))return;const i=await this.core.crypto.decode(r,n);try{e0(i)?(this.core.history.set(r,i),this.onRelayEventRequest({topic:r,payload:i})):Gl(i)&&(await this.core.history.resolve(i),await this.onRelayEventResponse({topic:r,payload:i}),this.core.history.delete(r,i.id))}catch(o){this.logger.error(o)}})}registerExpirerEvents(){this.core.expirer.on($n.expired,async e=>{const{topic:r}=ng(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(ra.expire,{topic:r}))})}}class RI extends W7{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.records=new Map,this.events=new Dr.exports.EventEmitter,this.name=cI,this.version=lI,this.cached=[],this.initialized=!1,this.storagePrefix=hs,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(n,i,o)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:i,chainId:o}),this.records.has(i.id))return;const c={id:i.id,topic:n,request:{method:i.method,params:i.params||null},chainId:o,expiry:Or(ye.THIRTY_DAYS)};this.records.set(c.id,c),this.persist(),this.events.emit(ei.created,c)},this.resolve=async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;const i=await this.getRecord(n.id);typeof i.response>"u"&&(i.response=Mn(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.persist(),this.events.emit(ei.updated,i))},this.get=async(n,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:i}),await this.getRecord(i)),this.delete=(n,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(o=>{if(o.topic===n){if(typeof i<"u"&&o.id!==i)return;this.records.delete(o.id),this.events.emit(ei.deleted,o)}}),this.persist()},this.exists=async(n,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===n:!1),this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=sn(r,this.name)}get context(){return nn(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;const n={topic:r.topic,request:ta(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(n)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const r=this.records.get(e);if(!r){const{message:n}=me("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(ei.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=me("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(ei.created,e=>{const r=ei.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(ei.updated,e=>{const r=ei.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(ei.deleted,e=>{const r=ei.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(uc.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{ye.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(ei.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=me("NOT_INITIALIZED",this.name);throw new Error(e)}}}class LI extends Z7{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.expirations=new Map,this.events=new Dr.exports.EventEmitter,this.name=uI,this.version=hI,this.cached=[],this.initialized=!1,this.storagePrefix=hs,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=n=>{try{const i=this.formatTarget(n);return typeof this.getExpiration(i)<"u"}catch{return!1}},this.set=(n,i)=>{this.isInitialized();const o=this.formatTarget(n),c={target:o,expiry:i};this.expirations.set(o,c),this.checkExpiry(o,c),this.events.emit($n.created,{target:o,expiration:c})},this.get=n=>{this.isInitialized();const i=this.formatTarget(n);return this.getExpiration(i)},this.del=n=>{if(this.isInitialized(),this.has(n)){const i=this.formatTarget(n),o=this.getExpiration(i);this.expirations.delete(i),this.events.emit($n.deleted,{target:i,expiration:o})}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=sn(r,this.name)}get context(){return nn(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return R8(e);if(typeof e=="number")return L8(e);const{message:r}=me("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit($n.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=me("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const r=this.expirations.get(e);if(!r){const{message:n}=me("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(n),new Error(n)}return r}checkExpiry(e,r){const{expiry:n}=r;ye.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit($n.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(uc.pulse,()=>this.checkExpirations()),this.events.on($n.created,e=>{const r=$n.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on($n.expired,e=>{const r=$n.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on($n.deleted,e=>{const r=$n.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=me("NOT_INITIALIZED",this.name);throw new Error(e)}}}class BI extends X7{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.name=o0,this.initialized=!1,this.queue=[],this.verifyDisabled=!1,this.init=async n=>{if(this.verifyDisabled||Uo()||!Fo())return;const i=this.getVerifyUrl(n?.verifyUrl);this.verifyUrl!==i&&this.removeIframe(),this.verifyUrl=i;try{await this.createIframe()}catch(o){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(o)}if(!this.initialized){this.removeIframe(),this.verifyUrl=a0;try{await this.createIframe()}catch(o){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(o),this.verifyDisabled=!0}}},this.register=async n=>{this.initialized?this.sendPost(n.attestationId):(this.addToQueue(n.attestationId),await this.init())},this.resolve=async n=>{if(this.isDevEnv)return"";const i=this.getVerifyUrl(n?.verifyUrl);let o;try{o=await this.fetchAttestation(n.attestationId,i)}catch(c){this.logger.info(`failed to resolve attestation: ${n.attestationId} from url: ${i}`),this.logger.info(c),o=await this.fetchAttestation(n.attestationId,a0)}return o},this.fetchAttestation=async(n,i)=>{this.logger.info(`resolving attestation: ${n} from url: ${i}`);const o=this.startAbortTimer(ye.ONE_SECOND*2),c=await fetch(`${i}/attestation/${n}`,{signal:this.abortController.signal});return clearTimeout(o),c.status===200?await c.json():void 0},this.addToQueue=n=>{this.queue.push(n)},this.processQueue=()=>{this.queue.length!==0&&(this.queue.forEach(n=>this.sendPost(n)),this.queue=[])},this.sendPost=n=>{var i;try{if(!this.iframe)return;(i=this.iframe.contentWindow)==null||i.postMessage(n,"*"),this.logger.info(`postMessage sent: ${n} ${this.verifyUrl}`)}catch{}},this.createIframe=async()=>{let n;const i=o=>{o.data==="verify_ready"&&(this.onInit(),window.removeEventListener("message",i),n())};await Promise.race([new Promise(o=>{const c=document.getElementById(o0);if(c)return this.iframe=c,this.onInit(),o();window.addEventListener("message",i);const l=document.createElement("iframe");l.id=o0,l.src=`${this.verifyUrl}/${this.projectId}`,l.style.display="none",document.body.append(l),this.iframe=l,n=o}),new Promise((o,c)=>setTimeout(()=>{window.removeEventListener("message",i),c("verify iframe load timeout")},ye.toMiliseconds(ye.FIVE_SECONDS)))])},this.onInit=()=>{this.initialized=!0,this.processQueue()},this.removeIframe=()=>{this.iframe&&(this.iframe.remove(),this.iframe=void 0,this.initialized=!1)},this.getVerifyUrl=n=>{let i=n||na;return fI.includes(i)||(this.logger.info(`verify url: ${i}, not included in trusted list, assigning default: ${na}`),i=na),i},this.logger=sn(r,this.name),this.verifyUrl=na,this.abortController=new AbortController,this.isDevEnv=Wa()&&process.env.IS_VITEST}get context(){return nn(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),ye.toMiliseconds(e))}}class UI extends ex{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.context=dI,this.registerDeviceToken=async n=>{const{clientId:i,token:o,notificationType:c,enableEncrypted:l=!1}=n,f=`${pI}/${this.projectId}/clients`;await f9(f,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:i,type:c,token:o,always_raw:l})})},this.logger=sn(r,this.context)}}var FI=Object.defineProperty,Qv=Object.getOwnPropertySymbols,jI=Object.prototype.hasOwnProperty,kI=Object.prototype.propertyIsEnumerable,Jv=(t,e,r)=>e in t?FI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Zv=(t,e)=>{for(var r in e||(e={}))jI.call(e,r)&&Jv(t,r,e[r]);if(Qv)for(var r of Qv(e))kI.call(e,r)&&Jv(t,r,e[r]);return t};class l0 extends K7{constructor(e){var r;super(e),this.protocol=Uv,this.version=US,this.name=s0,this.events=new Dr.exports.EventEmitter,this.initialized=!1,this.on=(c,l)=>this.events.on(c,l),this.once=(c,l)=>this.events.once(c,l),this.off=(c,l)=>this.events.off(c,l),this.removeListener=(c,l)=>this.events.removeListener(c,l),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||kv,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const n=Hl({level:typeof e?.logger=="string"&&e.logger?e.logger:FS.logger}),{logger:i,chunkLoggerController:o}=H7({opts:n,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=o,(r=this.logChunkController)!=null&&r.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var c,l;(c=this.logChunkController)!=null&&c.downloadLogsBlobInBrowser&&((l=this.logChunkController)==null||l.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=sn(i,this.name),this.heartbeat=new jf,this.crypto=new mI(this,this.logger,e?.keychain),this.history=new RI(this,this.logger),this.expirer=new LI(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new g7(Zv(Zv({},jS),e?.storageOptions)),this.relayer=new MI({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new NI(this,this.logger),this.verify=new BI(this.projectId||"",this.logger),this.echoClient=new UI(this.projectId||"",this.logger)}static async init(e){const r=new l0(e);await r.initialize();const n=await r.crypto.getClientId();return await r.storage.setItem(rI,n),r}get context(){return nn(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async 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}}}const qI=l0,Xv="wc",ew=2,tw="client",u0=`${Xv}@${ew}:${tw}:`,h0={name:tw,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},rw="WALLETCONNECT_DEEPLINK_CHOICE",zI="proposal",nw="Proposal expired",HI="session",ia=ye.SEVEN_DAYS,KI="engine",Tr={wc_sessionPropose:{req:{ttl:ye.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:ye.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:ye.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:ye.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:ye.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:ye.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:ye.ONE_DAY,prompt:!1,tag:1104},res:{ttl:ye.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:ye.ONE_DAY,prompt:!1,tag:1106},res:{ttl:ye.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:ye.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:ye.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:ye.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:ye.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:ye.ONE_DAY,prompt:!1,tag:1112},res:{ttl:ye.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:ye.ONE_DAY,prompt:!1,tag:1114},res:{ttl:ye.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:ye.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:ye.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:ye.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:ye.FIVE_MINUTES,prompt:!1,tag:1119}}},f0={min:ye.FIVE_MINUTES,max:ye.SEVEN_DAYS},Ai={idle:"IDLE",active:"ACTIVE"},WI="request",VI=["wc_sessionPropose","wc_sessionRequest","wc_authRequest"],GI="wc",YI="auth",QI="authKeys",JI="pairingTopics",ZI="requests",Ql=`${GI}@${1.5}:${YI}:`,Jl=`${Ql}:PUB_KEY`;var XI=Object.defineProperty,eD=Object.defineProperties,tD=Object.getOwnPropertyDescriptors,iw=Object.getOwnPropertySymbols,rD=Object.prototype.hasOwnProperty,nD=Object.prototype.propertyIsEnumerable,sw=(t,e,r)=>e in t?XI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,vr=(t,e)=>{for(var r in e||(e={}))rD.call(e,r)&&sw(t,r,e[r]);if(iw)for(var r of iw(e))nD.call(e,r)&&sw(t,r,e[r]);return t},Js=(t,e)=>eD(t,tD(e));class iD extends rx{constructor(e){super(e),this.name=KI,this.events=new Dr.exports,this.initialized=!1,this.requestQueue={state:Ai.idle,queue:[]},this.sessionRequestQueue={state:Ai.idle,queue:[]},this.requestQueueDelay=ye.ONE_SECOND,this.expectedPairingMethodMap=new Map,this.recentlyDeletedMap=new Map,this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),this.client.core.pairing.register({methods:Object.keys(Tr)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},ye.toMiliseconds(this.requestQueueDelay)))},this.connect=async r=>{await this.isInitialized();const n=Js(vr({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n);const{pairingTopic:i,requiredNamespaces:o,optionalNamespaces:c,sessionProperties:l,relays:f}=n;let h=i,g,_=!1;try{h&&(_=this.client.core.pairing.pairings.get(h).active)}catch(M){throw this.client.logger.error(`connect() -> pairing.get(${h}) failed`),M}if(!h||!_){const{topic:M,uri:U}=await this.client.core.pairing.create();h=M,g=U}if(!h){const{message:M}=me("NO_MATCHING_KEY",`connect() pairing topic: ${h}`);throw new Error(M)}const E=await this.client.core.crypto.generateKeyPair(),x=Tr.wc_sessionPropose.req.ttl||ye.FIVE_MINUTES,I=Or(x),k=vr({requiredNamespaces:o,optionalNamespaces:c,relays:f??[{protocol:jv}],proposer:{publicKey:E,metadata:this.client.metadata},expiryTimestamp:I,pairingTopic:h},l&&{sessionProperties:l}),{reject:W,resolve:Y,done:B}=qs(x,nw);this.events.once(wt("session_connect"),async({error:M,session:U})=>{if(M)W(M);else if(U){U.self.publicKey=E;const F=Js(vr({},U),{pairingTopic:k.pairingTopic,requiredNamespaces:k.requiredNamespaces,optionalNamespaces:k.optionalNamespaces});await this.client.session.set(U.topic,F),await this.setExpiry(U.topic,U.expiry),h&&await this.client.core.pairing.updateMetadata({topic:h,metadata:U.peer.metadata}),this.cleanupDuplicatePairings(F),Y(F)}});const z=await this.sendRequest({topic:h,method:"wc_sessionPropose",params:k,throwOnFailedPublish:!0});return await this.setProposal(z,vr({id:z},k)),{uri:g,approval:B}},this.pair=async r=>{await this.isInitialized();try{return await this.client.core.pairing.pair(r)}catch(n){throw this.client.logger.error("pair() failed"),n}},this.approve=async r=>{await this.isInitialized();try{await this.isValidApprove(r)}catch(B){throw this.client.logger.error("approve() -> isValidApprove() failed"),B}const{id:n,relayProtocol:i,namespaces:o,sessionProperties:c,sessionConfig:l}=r;let f;try{f=this.client.proposal.get(n)}catch(B){throw this.client.logger.error(`approve() -> proposal.get(${n}) failed`),B}const{pairingTopic:h,proposer:g,requiredNamespaces:_,optionalNamespaces:E}=f,x=await this.client.core.crypto.generateKeyPair(),I=g.publicKey,k=await this.client.core.crypto.generateSharedKey(x,I),W=vr(vr({relay:{protocol:i??"irn"},namespaces:o,controller:{publicKey:x,metadata:this.client.metadata},expiry:Or(ia)},c&&{sessionProperties:c}),l&&{sessionConfig:l});await this.client.core.relayer.subscribe(k);const Y=Js(vr({},W),{topic:k,requiredNamespaces:_,optionalNamespaces:E,pairingTopic:h,acknowledged:!1,self:W.controller,peer:{publicKey:g.publicKey,metadata:g.metadata},controller:x});await this.client.session.set(k,Y);try{await this.sendResult({id:n,topic:h,result:{relay:{protocol:i??"irn"},responderPublicKey:x},throwOnFailedPublish:!0}),await this.sendRequest({topic:k,method:"wc_sessionSettle",params:W,throwOnFailedPublish:!0})}catch(B){throw this.client.logger.error(B),this.client.session.delete(k,Ut("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(k),B}return await this.client.core.pairing.updateMetadata({topic:h,metadata:g.metadata}),await this.client.proposal.delete(n,Ut("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:h}),await this.setExpiry(k,Or(ia)),{topic:k,acknowledged:()=>new Promise(B=>setTimeout(()=>B(this.client.session.get(k)),500))}},this.reject=async r=>{await this.isInitialized();try{await this.isValidReject(r)}catch(c){throw this.client.logger.error("reject() -> isValidReject() failed"),c}const{id:n,reason:i}=r;let o;try{o=this.client.proposal.get(n).pairingTopic}catch(c){throw this.client.logger.error(`reject() -> proposal.get(${n}) failed`),c}o&&(await this.sendError({id:n,topic:o,error:i,rpcOpts:Tr.wc_sessionPropose.reject}),await this.client.proposal.delete(n,Ut("USER_DISCONNECTED")))},this.update=async r=>{await this.isInitialized();try{await this.isValidUpdate(r)}catch(_){throw this.client.logger.error("update() -> isValidUpdate() failed"),_}const{topic:n,namespaces:i}=r,{done:o,resolve:c,reject:l}=qs(),f=us(),h=Ys().toString(),g=this.client.session.get(n).namespaces;return this.events.once(wt("session_update",f),({error:_})=>{_?l(_):c()}),await this.client.session.update(n,{namespaces:i}),await this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:f,relayRpcId:h}).catch(_=>{this.client.logger.error(_),this.client.session.update(n,{namespaces:g}),l(_)}),{acknowledged:o}},this.extend=async r=>{await this.isInitialized();try{await this.isValidExtend(r)}catch(f){throw this.client.logger.error("extend() -> isValidExtend() failed"),f}const{topic:n}=r,i=us(),{done:o,resolve:c,reject:l}=qs();return this.events.once(wt("session_extend",i),({error:f})=>{f?l(f):c()}),await this.setExpiry(n,Or(ia)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(f=>{l(f)}),{acknowledged:o}},this.request=async r=>{await this.isInitialized();try{await this.isValidRequest(r)}catch(x){throw this.client.logger.error("request() -> isValidRequest() failed"),x}const{chainId:n,request:i,topic:o,expiry:c=Tr.wc_sessionRequest.req.ttl}=r,l=this.client.session.get(o),f=us(),h=Ys().toString(),{done:g,resolve:_,reject:E}=qs(c,"Request expired. Please try again.");return this.events.once(wt("session_request",f),({error:x,result:I})=>{x?E(x):_(I)}),await Promise.all([new Promise(async x=>{await this.sendRequest({clientRpcId:f,relayRpcId:h,topic:o,method:"wc_sessionRequest",params:{request:Js(vr({},i),{expiryTimestamp:Or(c)}),chainId:n},expiry:c,throwOnFailedPublish:!0}).catch(I=>E(I)),this.client.events.emit("session_request_sent",{topic:o,request:i,chainId:n,id:f}),x()}),new Promise(async x=>{var I;if(!((I=l.sessionConfig)!=null&&I.disableDeepLink)){const k=await U8(this.client.core.storage,rw);B8({id:f,topic:o,wcDeepLink:k})}x()}),g()]).then(x=>x[2])},this.respond=async r=>{await this.isInitialized(),await this.isValidRespond(r);const{topic:n,response:i}=r,{id:o}=i;_i(i)?await this.sendResult({id:o,topic:n,result:i.result,throwOnFailedPublish:!0}):Mn(i)&&await this.sendError({id:o,topic:n,error:i.error}),this.cleanupAfterResponse(r)},this.ping=async r=>{await this.isInitialized();try{await this.isValidPing(r)}catch(i){throw this.client.logger.error("ping() -> isValidPing() failed"),i}const{topic:n}=r;if(this.client.session.keys.includes(n)){const i=us(),o=Ys().toString(),{done:c,resolve:l,reject:f}=qs();this.events.once(wt("session_ping",i),({error:h})=>{h?f(h):l()}),await Promise.all([this.sendRequest({topic:n,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:i,relayRpcId:o}),c()])}else this.client.core.pairing.pairings.keys.includes(n)&&await this.client.core.pairing.ping({topic:n})},this.emit=async r=>{await this.isInitialized(),await this.isValidEmit(r);const{topic:n,event:i,chainId:o}=r,c=Ys().toString();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:i,chainId:o},throwOnFailedPublish:!0,relayRpcId:c})},this.disconnect=async r=>{await this.isInitialized(),await this.isValidDisconnect(r);const{topic:n}=r;if(this.client.session.keys.includes(n))await this.sendRequest({topic:n,method:"wc_sessionDelete",params:Ut("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:n,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(n))await this.client.core.pairing.disconnect({topic:n});else{const{message:i}=me("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(i)}},this.find=r=>(this.isInitialized(),this.client.session.getAll().filter(n=>lA(n,r))),this.getPendingSessionRequests=()=>this.client.pendingRequest.getAll(),this.authenticate=async r=>{this.isInitialized(),this.isValidAuthenticate(r);const{chains:n,statement:i="",uri:o,domain:c,nonce:l,type:f,exp:h,nbf:g,methods:_=[],expiry:E}=r,x=[...r.resources||[]],{topic:I,uri:k}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"]});this.client.logger.info({message:"Generated new pairing",pairing:{topic:I,uri:k}});const W=await this.client.core.crypto.generateKeyPair(),Y=Tl(W);if(await Promise.all([this.client.auth.authKeys.set(Jl,{responseTopic:Y,publicKey:W}),this.client.auth.pairingTopics.set(Y,{topic:Y,pairingTopic:I})]),await this.client.core.relayer.subscribe(Y),this.client.logger.info(`sending request to new pairing topic: ${I}`),_.length>0){const{namespace:d}=ml(n[0]);let p=TE(d,"request",_);$l(x)&&(p=RE(p,x.pop())),x.push(p)}const B=E&&E>Tr.wc_sessionAuthenticate.req.ttl?E:Tr.wc_sessionAuthenticate.req.ttl,z={authPayload:{type:f??"caip122",chains:n,statement:i,aud:o,domain:c,version:"1",nonce:l,iat:new Date().toISOString(),exp:h,nbf:g,resources:x},requester:{publicKey:W,metadata:this.client.metadata},expiryTimestamp:Or(B)},M={eip155:{chains:n,methods:[...new Set(["personal_sign",..._])],events:["chainChanged","accountsChanged"]}},U={requiredNamespaces:{},optionalNamespaces:M,relays:[{protocol:"irn"}],pairingTopic:I,proposer:{publicKey:W,metadata:this.client.metadata},expiryTimestamp:Or(Tr.wc_sessionPropose.req.ttl)},{done:F,resolve:m,reject:$}=qs(B,"Request expired"),te=async({error:d,session:p})=>{if(this.events.off(wt("session_request",ne),ee),d)$(d);else if(p){p.self.publicKey=W,await this.client.session.set(p.topic,p),await this.setExpiry(p.topic,p.expiry),I&&await this.client.core.pairing.updateMetadata({topic:I,metadata:p.peer.metadata});const b=this.client.session.get(p.topic);await this.deleteProposal(de),m({session:b})}},ee=async d=>{if(await this.deletePendingAuthRequest(ne,{message:"fulfilled",code:0}),d.error){const C=Ut("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return d.error.code===C.code?void 0:(this.events.off(wt("session_connect"),te),$(d.error.message))}await this.deleteProposal(de),this.events.off(wt("session_connect"),te);const{cacaos:p,responder:b}=d.result,D=[],O=[];for(const C of p){await hm({cacao:C,projectId:this.client.core.projectId})||(this.client.logger.error(C,"Signature verification failed"),$(Ut("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:v}=C,N=$l(v.resources),oe=[um(v.iss)],pe=Pl(v.iss);if(N){const A=pm(N),re=gm(N);D.push(...A),oe.push(...re)}for(const A of oe)O.push(`${A}:${pe}`)}const T=await this.client.core.crypto.generateSharedKey(W,b.publicKey);let L;D.length>0&&(L={topic:T,acknowledged:!0,self:{publicKey:W,metadata:this.client.metadata},peer:b,controller:b.publicKey,expiry:Or(ia),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:I,namespaces:Sm([...new Set(D)],[...new Set(O)])},await this.client.core.relayer.subscribe(T),await this.client.session.set(T,L),L=this.client.session.get(T)),m({auths:p,session:L})},ne=us(),de=us();this.events.once(wt("session_connect"),te),this.events.once(wt("session_request",ne),ee);try{await Promise.all([this.sendRequest({topic:I,method:"wc_sessionAuthenticate",params:z,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:ne}),this.sendRequest({topic:I,method:"wc_sessionPropose",params:U,expiry:Tr.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:de})])}catch(d){throw this.events.off(wt("session_connect"),te),this.events.off(wt("session_request",ne),ee),d}return await this.setProposal(de,vr({id:de},U)),await this.setAuthRequest(ne,{request:Js(vr({},z),{verifyContext:{}}),pairingTopic:I}),{uri:k,response:F}},this.approveSessionAuthenticate=async r=>{this.isInitialized();const{id:n,auths:i}=r,o=this.getPendingAuthRequest(n);if(!o)throw new Error(`Could not find pending auth request with id ${n}`);const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),f=Tl(c),h={type:ji,receiverPublicKey:c,senderPublicKey:l},g=[],_=[];for(const I of i){if(!await hm({cacao:I,projectId:this.client.core.projectId})){const z=Ut("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:f,error:z,encodeOpts:h}),new Error(z.message)}const{p:k}=I,W=$l(k.resources),Y=[um(k.iss)],B=Pl(k.iss);if(W){const z=pm(W),M=gm(W);g.push(...z),Y.push(...M)}for(const z of Y)_.push(`${z}:${B}`)}const E=await this.client.core.crypto.generateSharedKey(l,c);let x;return g?.length>0&&(x={topic:E,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:Or(ia),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:"",namespaces:Sm([...new Set(g)],[...new Set(_)])},await this.client.core.relayer.subscribe(E),await this.client.session.set(E,x)),await this.sendResult({topic:f,id:n,result:{cacaos:i,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0}),await this.client.auth.requests.delete(n,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),{session:x}},this.rejectSessionAuthenticate=async r=>{await this.isInitialized();const{id:n,reason:i}=r,o=this.getPendingAuthRequest(n);if(!o)throw new Error(`Could not find pending auth request with id ${n}`);const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),f=Tl(c),h={type:ji,receiverPublicKey:c,senderPublicKey:l};await this.sendError({id:n,topic:f,error:i,encodeOpts:h,rpcOpts:Tr.wc_sessionAuthenticate.reject}),await this.client.auth.requests.delete(n,{message:"rejected",code:0}),await this.client.proposal.delete(n,Ut("USER_DISCONNECTED"))},this.formatAuthMessage=r=>{this.isInitialized();const{request:n,iss:i}=r;return fm(n,i)},this.cleanupDuplicatePairings=async r=>{if(r.pairingTopic)try{const n=this.client.core.pairing.pairings.get(r.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(o=>{var c,l;return((c=o.peerMetadata)==null?void 0:c.url)&&((l=o.peerMetadata)==null?void 0:l.url)===r.peer.metadata.url&&o.topic&&o.topic!==n.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(o=>this.client.core.pairing.disconnect({topic:o.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}},this.deleteSession=async r=>{var n;const{topic:i,expirerHasDeleted:o=!1,emitEvent:c=!0,id:l=0}=r,{self:f}=this.client.session.get(i);await this.client.core.relayer.unsubscribe(i),await this.client.session.delete(i,Ut("USER_DISCONNECTED")),this.addToRecentlyDeleted(i,"session"),this.client.core.crypto.keychain.has(f.publicKey)&&await this.client.core.crypto.deleteKeyPair(f.publicKey),this.client.core.crypto.keychain.has(i)&&await this.client.core.crypto.deleteSymKey(i),o||this.client.core.expirer.del(i),this.client.core.storage.removeItem(rw).catch(h=>this.client.logger.warn(h)),this.getPendingSessionRequests().forEach(h=>{h.topic===i&&this.deletePendingSessionRequest(h.id,Ut("USER_DISCONNECTED"))}),i===((n=this.sessionRequestQueue.queue[0])==null?void 0:n.topic)&&(this.sessionRequestQueue.state=Ai.idle),c&&this.client.events.emit("session_delete",{id:l,topic:i})},this.deleteProposal=async(r,n)=>{await Promise.all([this.client.proposal.delete(r,Ut("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")},this.deletePendingSessionRequest=async(r,n,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(o=>o.id!==r),i&&(this.sessionRequestQueue.state=Ai.idle,this.client.events.emit("session_request_expire",{id:r}))},this.deletePendingAuthRequest=async(r,n,i=!1)=>{await Promise.all([this.client.auth.requests.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)])},this.setExpiry=async(r,n)=>{this.client.session.keys.includes(r)&&(this.client.core.expirer.set(r,n),await this.client.session.update(r,{expiry:n}))},this.setProposal=async(r,n)=>{this.client.core.expirer.set(r,Or(Tr.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,n)},this.setAuthRequest=async(r,n)=>{const{request:i,pairingTopic:o}=n;this.client.core.expirer.set(r,i.expiryTimestamp),await this.client.auth.requests.set(r,{authPayload:i.authPayload,requester:i.requester,expiryTimestamp:i.expiryTimestamp,id:r,pairingTopic:o,verifyContext:i.verifyContext})},this.setPendingSessionRequest=async r=>{const{id:n,topic:i,params:o,verifyContext:c}=r,l=o.request.expiryTimestamp||Or(Tr.wc_sessionRequest.req.ttl);this.client.core.expirer.set(n,l),await this.client.pendingRequest.set(n,{id:n,topic:i,params:o,verifyContext:c})},this.sendRequest=async r=>{const{topic:n,method:i,params:o,expiry:c,relayRpcId:l,clientRpcId:f,throwOnFailedPublish:h}=r,g=ta(i,o,f);if(Fo()&&VI.includes(i)){const x=Ws(JSON.stringify(g));this.client.core.verify.register({attestationId:x})}let _;try{_=await this.client.core.crypto.encode(n,g)}catch(x){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),x}const E=Tr[i].req;return c&&(E.ttl=c),l&&(E.id=l),this.client.core.history.set(n,g),h?(E.internal=Js(vr({},E.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,_,E)):this.client.core.relayer.publish(n,_,E).catch(x=>this.client.logger.error(x)),g.id},this.sendResult=async r=>{const{id:n,topic:i,result:o,throwOnFailedPublish:c,encodeOpts:l}=r,f=Wl(n,o);let h;try{h=await this.client.core.crypto.encode(i,f,l)}catch(E){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),E}let g;try{g=await this.client.core.history.get(i,n)}catch(E){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${n}) failed`),E}const _=Tr[g.request.method].res;c?(_.internal=Js(vr({},_.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,h,_)):this.client.core.relayer.publish(i,h,_).catch(E=>this.client.logger.error(E)),await this.client.core.history.resolve(f)},this.sendError=async r=>{const{id:n,topic:i,error:o,encodeOpts:c,rpcOpts:l}=r,f=Vl(n,o);let h;try{h=await this.client.core.crypto.encode(i,f,c)}catch(E){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),E}let g;try{g=await this.client.core.history.get(i,n)}catch(E){throw this.client.logger.error(`sendError() -> history.get(${i}, ${n}) failed`),E}const _=l||Tr[g.request.method].res;this.client.core.relayer.publish(i,h,_),await this.client.core.history.resolve(f)},this.cleanup=async()=>{const r=[],n=[];this.client.session.getAll().forEach(i=>{let o=!1;os(i.expiry)&&(o=!0),this.client.core.crypto.keychain.has(i.topic)||(o=!0),o&&r.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{os(i.expiryTimestamp)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession({topic:i})),...n.map(i=>this.deleteProposal(i))])},this.onRelayEventRequest=async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state===Ai.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=Ai.active;const r=this.requestQueue.queue.shift();if(r)try{this.processRequest(r),await new Promise(n=>setTimeout(n,300))}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=Ai.idle},this.processRequest=r=>{const{topic:n,payload:i}=r,o=i.method;if(!this.shouldIgnorePairingRequest({topic:n,requestMethod:o}))switch(o){case"wc_sessionPropose":return this.onSessionProposeRequest(n,i);case"wc_sessionSettle":return this.onSessionSettleRequest(n,i);case"wc_sessionUpdate":return this.onSessionUpdateRequest(n,i);case"wc_sessionExtend":return this.onSessionExtendRequest(n,i);case"wc_sessionPing":return this.onSessionPingRequest(n,i);case"wc_sessionDelete":return this.onSessionDeleteRequest(n,i);case"wc_sessionRequest":return this.onSessionRequest(n,i);case"wc_sessionEvent":return this.onSessionEventRequest(n,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateRequest(n,i);default:return this.client.logger.info(`Unsupported request method ${o}`)}},this.onRelayEventResponse=async r=>{const{topic:n,payload:i}=r,o=(await this.client.core.history.get(n,i.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(n,i);case"wc_sessionSettle":return this.onSessionSettleResponse(n,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,i);case"wc_sessionExtend":return this.onSessionExtendResponse(n,i);case"wc_sessionPing":return this.onSessionPingResponse(n,i);case"wc_sessionRequest":return this.onSessionRequestResponse(n,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(n,i);default:return this.client.logger.info(`Unsupported response method ${o}`)}},this.onRelayEventUnknownPayload=r=>{const{topic:n}=r,{message:i}=me("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)},this.shouldIgnorePairingRequest=r=>{const{topic:n,requestMethod:i}=r,o=this.expectedPairingMethodMap.get(n);return!o||o.includes(i)?!1:!!(o.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)},this.onSessionProposeRequest=async(r,n)=>{const{params:i,id:o}=n;try{this.isValidConnect(vr({},n.params));const c=i.expiryTimestamp||Or(Tr.wc_sessionPropose.req.ttl),l=vr({id:o,pairingTopic:r,expiryTimestamp:c},i);await this.setProposal(o,l);const f=Ws(JSON.stringify(n)),h=await this.getVerifyContext(f,l.proposer.metadata);this.client.events.emit("session_proposal",{id:o,params:l,verifyContext:h})}catch(c){await this.sendError({id:o,topic:r,error:c,rpcOpts:Tr.wc_sessionPropose.autoReject}),this.client.logger.error(c)}},this.onSessionProposeResponse=async(r,n)=>{const{id:i}=n;if(_i(n)){const{result:o}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const c=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:c});const l=c.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:l});const f=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:f});const h=await this.client.core.crypto.generateSharedKey(l,f);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:h});const g=await this.client.core.relayer.subscribe(h);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:g}),await this.client.core.pairing.activate({topic:r})}else if(Mn(n)){await this.client.proposal.delete(i,Ut("USER_DISCONNECTED"));const o=wt("session_connect");if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(wt("session_connect"),{error:n.error})}},this.onSessionSettleRequest=async(r,n)=>{const{id:i,params:o}=n;try{this.isValidSessionSettleRequest(o);const{relay:c,controller:l,expiry:f,namespaces:h,sessionProperties:g,sessionConfig:_}=n.params,E=vr(vr({topic:r,relay:c,expiry:f,namespaces:h,acknowledged:!0,pairingTopic:"",requiredNamespaces:{},optionalNamespaces:{},controller:l.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:l.publicKey,metadata:l.metadata}},g&&{sessionProperties:g}),_&&{sessionConfig:_});await this.sendResult({id:n.id,topic:r,result:!0,throwOnFailedPublish:!0});const x=wt("session_connect");if(this.events.listenerCount(x)===0)throw new Error(`emitting ${x} without any listeners 997`);this.events.emit(wt("session_connect"),{session:E})}catch(c){await this.sendError({id:i,topic:r,error:c}),this.client.logger.error(c)}},this.onSessionSettleResponse=async(r,n)=>{const{id:i}=n;_i(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(wt("session_approve",i),{})):Mn(n)&&(await this.client.session.delete(r,Ut("USER_DISCONNECTED")),this.events.emit(wt("session_approve",i),{error:n.error}))},this.onSessionUpdateRequest=async(r,n)=>{const{params:i,id:o}=n;try{const c=`${r}_session_update`,l=ac.get(c);if(l&&this.isRequestOutOfSync(l,o)){this.client.logger.info(`Discarding out of sync request - ${o}`),this.sendError({id:o,topic:r,error:Ut("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(vr({topic:r},i));try{ac.set(c,o),await this.client.session.update(r,{namespaces:i.namespaces}),await this.sendResult({id:o,topic:r,result:!0,throwOnFailedPublish:!0})}catch(f){throw ac.delete(c),f}this.client.events.emit("session_update",{id:o,topic:r,params:i})}catch(c){await this.sendError({id:o,topic:r,error:c}),this.client.logger.error(c)}},this.isRequestOutOfSync=(r,n)=>parseInt(n.toString().slice(0,-3))<=parseInt(r.toString().slice(0,-3)),this.onSessionUpdateResponse=(r,n)=>{const{id:i}=n,o=wt("session_update",i);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners`);_i(n)?this.events.emit(wt("session_update",i),{}):Mn(n)&&this.events.emit(wt("session_update",i),{error:n.error})},this.onSessionExtendRequest=async(r,n)=>{const{id:i}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,Or(ia)),await this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:i,topic:r})}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}},this.onSessionExtendResponse=(r,n)=>{const{id:i}=n,o=wt("session_extend",i);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners`);_i(n)?this.events.emit(wt("session_extend",i),{}):Mn(n)&&this.events.emit(wt("session_extend",i),{error:n.error})},this.onSessionPingRequest=async(r,n)=>{const{id:i}=n;try{this.isValidPing({topic:r}),await this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:i,topic:r})}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}},this.onSessionPingResponse=(r,n)=>{const{id:i}=n,o=wt("session_ping",i);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners`);setTimeout(()=>{_i(n)?this.events.emit(wt("session_ping",i),{}):Mn(n)&&this.events.emit(wt("session_ping",i),{error:n.error})},500)},this.onSessionDeleteRequest=async(r,n)=>{const{id:i}=n;try{this.isValidDisconnect({topic:r,reason:n.params}),await Promise.all([new Promise(o=>{this.client.core.relayer.once(on.publish,async()=>{o(await this.deleteSession({topic:r,id:i}))})}),this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:r,error:Ut("USER_DISCONNECTED")})])}catch(o){this.client.logger.error(o)}},this.onSessionRequest=async(r,n)=>{var i;const{id:o,params:c}=n;try{await this.isValidRequest(vr({topic:r},c));const l=Ws(JSON.stringify(ta("wc_sessionRequest",c,o))),f=this.client.session.get(r),h=await this.getVerifyContext(l,f.peer.metadata),g={id:o,topic:r,params:c,verifyContext:h};await this.setPendingSessionRequest(g),(i=this.client.signConfig)!=null&&i.disableRequestQueue?this.emitSessionRequest(g):(this.addSessionRequestToSessionRequestQueue(g),this.processSessionRequestQueue())}catch(l){await this.sendError({id:o,topic:r,error:l}),this.client.logger.error(l)}},this.onSessionRequestResponse=(r,n)=>{const{id:i}=n,o=wt("session_request",i);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners`);_i(n)?this.events.emit(wt("session_request",i),{result:n.result}):Mn(n)&&this.events.emit(wt("session_request",i),{error:n.error})},this.onSessionEventRequest=async(r,n)=>{const{id:i,params:o}=n;try{const c=`${r}_session_event_${o.event.name}`,l=ac.get(c);if(l&&this.isRequestOutOfSync(l,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(vr({topic:r},o)),this.client.events.emit("session_event",{id:i,topic:r,params:o}),ac.set(c,i)}catch(c){await this.sendError({id:i,topic:r,error:c}),this.client.logger.error(c)}},this.onSessionAuthenticateResponse=(r,n)=>{const{id:i}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:n}),_i(n)?this.events.emit(wt("session_request",i),{result:n.result}):Mn(n)&&this.events.emit(wt("session_request",i),{error:n.error})},this.onSessionAuthenticateRequest=async(r,n)=>{try{const{requester:i,authPayload:o,expiryTimestamp:c}=n.params,l=Ws(JSON.stringify(n)),f=await this.getVerifyContext(l,this.client.metadata),h={requester:i,pairingTopic:r,id:n.id,authPayload:o,verifyContext:f,expiryTimestamp:c};await this.setAuthRequest(n.id,{request:h,pairingTopic:r}),this.client.events.emit("session_authenticate",{topic:r,params:n.params,id:n.id})}catch(i){this.client.logger.error(i);const o=n.params.requester.publicKey,c=await this.client.core.crypto.generateKeyPair(),l={type:ji,receiverPublicKey:o,senderPublicKey:c};await this.sendError({id:n.id,topic:r,error:i,encodeOpts:l,rpcOpts:Tr.wc_sessionAuthenticate.autoReject})}},this.addSessionRequestToSessionRequestQueue=r=>{this.sessionRequestQueue.queue.push(r)},this.cleanupAfterResponse=r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Ai.idle,this.processSessionRequestQueue()},ye.toMiliseconds(this.requestQueueDelay))},this.cleanupPendingSentRequestsForTopic=({topic:r,error:n})=>{const i=this.client.core.history.pending;i.length>0&&i.filter(o=>o.topic===r&&o.request.method==="wc_sessionRequest").forEach(o=>{const c=o.request.id,l=wt("session_request",c);if(this.events.listenerCount(l)===0)throw new Error(`emitting ${l} without any listeners`);this.events.emit(wt("session_request",o.request.id),{error:n})})},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===Ai.active){this.client.logger.info("session request queue is already active.");return}const r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=Ai.active,this.emitSessionRequest(r)}catch(n){this.client.logger.error(n)}},this.emitSessionRequest=r=>{this.client.events.emit("session_request",r)},this.onPairingCreated=r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;const n=this.client.proposal.getAll().find(i=>i.pairingTopic===r.topic);n&&this.onSessionProposeRequest(r.topic,ta("wc_sessionPropose",{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties},n.id))},this.isValidConnect=async r=>{if(!tn(r)){const{message:f}=me("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(f)}const{pairingTopic:n,requiredNamespaces:i,optionalNamespaces:o,sessionProperties:c,relays:l}=r;if(Hr(n)||await this.isValidPairingTopic(n),!_A(l,!0)){const{message:f}=me("MISSING_OR_INVALID",`connect() relays: ${l}`);throw new Error(f)}!Hr(i)&&oc(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!Hr(o)&&oc(o)!==0&&this.validateNamespaces(o,"optionalNamespaces"),Hr(c)||this.validateSessionProps(c,"sessionProperties")},this.validateNamespaces=(r,n)=>{const i=bA(r,"connect()",n);if(i)throw new Error(i.message)},this.isValidApprove=async r=>{if(!tn(r))throw new Error(me("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:n,namespaces:i,relayProtocol:o,sessionProperties:c}=r;this.checkRecentlyDeleted(n),await this.isValidProposalId(n);const l=this.client.proposal.get(n),f=Rf(i,"approve()");if(f)throw new Error(f.message);const h=Mm(l.requiredNamespaces,i,"approve()");if(h)throw new Error(h.message);if(!ur(o,!0)){const{message:g}=me("MISSING_OR_INVALID",`approve() relayProtocol: ${o}`);throw new Error(g)}Hr(c)||this.validateSessionProps(c,"sessionProperties")},this.isValidReject=async r=>{if(!tn(r)){const{message:o}=me("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(o)}const{id:n,reason:i}=r;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!AA(i)){const{message:o}=me("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(o)}},this.isValidSessionSettleRequest=r=>{if(!tn(r)){const{message:h}=me("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(h)}const{relay:n,controller:i,namespaces:o,expiry:c}=r;if(!Cm(n)){const{message:h}=me("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(h)}const l=pA(i,"onSessionSettleRequest()");if(l)throw new Error(l.message);const f=Rf(o,"onSessionSettleRequest()");if(f)throw new Error(f.message);if(os(c)){const{message:h}=me("EXPIRED","onSessionSettleRequest()");throw new Error(h)}},this.isValidUpdate=async r=>{if(!tn(r)){const{message:f}=me("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(f)}const{topic:n,namespaces:i}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);const o=this.client.session.get(n),c=Rf(i,"update()");if(c)throw new Error(c.message);const l=Mm(o.requiredNamespaces,i,"update()");if(l)throw new Error(l.message)},this.isValidExtend=async r=>{if(!tn(r)){const{message:i}=me("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(i)}const{topic:n}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)},this.isValidRequest=async r=>{if(!tn(r)){const{message:f}=me("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(f)}const{topic:n,request:i,chainId:o,expiry:c}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);const{namespaces:l}=this.client.session.get(n);if(!Om(l,o)){const{message:f}=me("MISSING_OR_INVALID",`request() chainId: ${o}`);throw new Error(f)}if(!xA(i)){const{message:f}=me("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(f)}if(!DA(l,o,i.method)){const{message:f}=me("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(f)}if(c&&!PA(c,f0)){const{message:f}=me("MISSING_OR_INVALID",`request() expiry: ${c}. Expiry must be a number (in seconds) between ${f0.min} and ${f0.max}`);throw new Error(f)}},this.isValidRespond=async r=>{var n;if(!tn(r)){const{message:c}=me("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(c)}const{topic:i,response:o}=r;try{await this.isValidSessionTopic(i)}catch(c){throw(n=r?.response)!=null&&n.id&&this.cleanupAfterResponse(r),c}if(!SA(o)){const{message:c}=me("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(o)}`);throw new Error(c)}},this.isValidPing=async r=>{if(!tn(r)){const{message:i}=me("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.isValidEmit=async r=>{if(!tn(r)){const{message:l}=me("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(l)}const{topic:n,event:i,chainId:o}=r;await this.isValidSessionTopic(n);const{namespaces:c}=this.client.session.get(n);if(!Om(c,o)){const{message:l}=me("MISSING_OR_INVALID",`emit() chainId: ${o}`);throw new Error(l)}if(!IA(i)){const{message:l}=me("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(l)}if(!CA(c,o,i.name)){const{message:l}=me("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(l)}},this.isValidDisconnect=async r=>{if(!tn(r)){const{message:i}=me("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.isValidAuthenticate=r=>{const{chains:n,uri:i,domain:o,nonce:c}=r;if(!Array.isArray(n)||n.length===0)throw new Error("chains is required and must be a non-empty array");if(!ur(i,!1))throw new Error("uri is required parameter");if(!ur(o,!1))throw new Error("domain is required parameter");if(!ur(c,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(f=>ml(f).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:l}=ml(n[0]);if(l!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")},this.getVerifyContext=async(r,n)=>{const i={verified:{verifyUrl:n.verifyUrl||na,validation:"UNKNOWN",origin:n.url||""}};try{const o=await this.client.core.verify.resolve({attestationId:r,verifyUrl:n.verifyUrl});o&&(i.verified.origin=o.origin,i.verified.isScam=o.isScam,i.verified.validation=o.origin===new URL(n.url).origin?"VALID":"INVALID")}catch(o){this.client.logger.info(o)}return this.client.logger.info(`Verify context: ${JSON.stringify(i)}`),i},this.validateSessionProps=(r,n)=>{Object.values(r).forEach(i=>{if(!ur(i,!1)){const{message:o}=me("MISSING_OR_INVALID",`${n} must be in Record<string, string> format. Received: ${JSON.stringify(i)}`);throw new Error(o)}})},this.getPendingAuthRequest=r=>{const n=this.client.auth.requests.get(r);return typeof n=="object"?n:void 0},this.addToRecentlyDeleted=(r,n)=>{if(this.recentlyDeletedMap.set(r,n),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let i=0;const o=this.recentlyDeletedLimit/2;for(const c of this.recentlyDeletedMap.keys()){if(i++>=o)break;this.recentlyDeletedMap.delete(c)}}},this.checkRecentlyDeleted=r=>{const n=this.recentlyDeletedMap.get(r);if(n){const{message:i}=me("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${r}`);throw new Error(i)}}}async isInitialized(){if(!this.initialized){const{message:e}=me("NOT_INITIALIZED",this.name);throw new Error(e)}await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(on.message,async e=>{const{topic:r,message:n}=e,{publicKey:i}=this.client.auth.authKeys.keys.includes(Jl)?this.client.auth.authKeys.get(Jl):{responseTopic:void 0,publicKey:void 0},o=await this.client.core.crypto.decode(r,n,{receiverPublicKey:i});try{e0(o)?(this.client.core.history.set(r,o),this.onRelayEventRequest({topic:r,payload:o})):Gl(o)?(await this.client.core.history.resolve(o),await this.onRelayEventResponse({topic:r,payload:o}),this.client.core.history.delete(r,o.id)):this.onRelayEventUnknownPayload({topic:r,payload:o})}catch(c){this.client.logger.error(c)}})}registerExpirerEvents(){this.client.core.expirer.on($n.expired,async e=>{const{topic:r,id:n}=ng(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,me("EXPIRED"),!0);if(n&&this.client.auth.requests.keys.includes(n))return await this.deletePendingAuthRequest(n,me("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}registerPairingEvents(){this.client.core.pairing.events.on(ra.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(ra.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!ur(e,!1)){const{message:r}=me("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:r}=me("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(os(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=me("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!ur(e,!1)){const{message:r}=me("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:r}=me("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(os(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=me("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=me("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(ur(e,!1)){const{message:r}=me("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=me("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!EA(e)){const{message:r}=me("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=me("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(os(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=me("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class sD extends Qs{constructor(e,r){super(e,r,zI,u0),this.core=e,this.logger=r}}class oD extends Qs{constructor(e,r){super(e,r,HI,u0),this.core=e,this.logger=r}}class aD extends Qs{constructor(e,r){super(e,r,WI,u0,n=>n.id),this.core=e,this.logger=r}}class cD extends Qs{constructor(e,r){super(e,r,QI,Ql,()=>Jl),this.core=e,this.logger=r}}class lD extends Qs{constructor(e,r){super(e,r,JI,Ql),this.core=e,this.logger=r}}class uD extends Qs{constructor(e,r){super(e,r,ZI,Ql,n=>n.id),this.core=e,this.logger=r}}class hD{constructor(e,r){this.core=e,this.logger=r,this.authKeys=new cD(this.core,this.logger),this.pairingTopics=new lD(this.core,this.logger),this.requests=new uD(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}class d0 extends tx{constructor(e){super(e),this.protocol=Xv,this.version=ew,this.name=h0.name,this.events=new Dr.exports.EventEmitter,this.on=(n,i)=>this.events.on(n,i),this.once=(n,i)=>this.events.once(n,i),this.off=(n,i)=>this.events.off(n,i),this.removeListener=(n,i)=>this.events.removeListener(n,i),this.removeAllListeners=n=>this.events.removeAllListeners(n),this.connect=async n=>{try{return await this.engine.connect(n)}catch(i){throw this.logger.error(i.message),i}},this.pair=async n=>{try{return await this.engine.pair(n)}catch(i){throw this.logger.error(i.message),i}},this.approve=async n=>{try{return await this.engine.approve(n)}catch(i){throw this.logger.error(i.message),i}},this.reject=async n=>{try{return await this.engine.reject(n)}catch(i){throw this.logger.error(i.message),i}},this.update=async n=>{try{return await this.engine.update(n)}catch(i){throw this.logger.error(i.message),i}},this.extend=async n=>{try{return await this.engine.extend(n)}catch(i){throw this.logger.error(i.message),i}},this.request=async n=>{try{return await this.engine.request(n)}catch(i){throw this.logger.error(i.message),i}},this.respond=async n=>{try{return await this.engine.respond(n)}catch(i){throw this.logger.error(i.message),i}},this.ping=async n=>{try{return await this.engine.ping(n)}catch(i){throw this.logger.error(i.message),i}},this.emit=async n=>{try{return await this.engine.emit(n)}catch(i){throw this.logger.error(i.message),i}},this.disconnect=async n=>{try{return await this.engine.disconnect(n)}catch(i){throw this.logger.error(i.message),i}},this.find=n=>{try{return this.engine.find(n)}catch(i){throw this.logger.error(i.message),i}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}},this.authenticate=async n=>{try{return await this.engine.authenticate(n)}catch(i){throw this.logger.error(i.message),i}},this.formatAuthMessage=n=>{try{return this.engine.formatAuthMessage(n)}catch(i){throw this.logger.error(i.message),i}},this.approveSessionAuthenticate=async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}},this.rejectSessionAuthenticate=async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}},this.name=e?.name||h0.name,this.metadata=e?.metadata||M8(),this.signConfig=e?.signConfig;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:yi(Hl({level:e?.logger||h0.logger}));this.core=e?.core||new qI(e),this.logger=sn(r,this.name),this.session=new oD(this.core,this.logger),this.proposal=new sD(this.core,this.logger),this.pendingRequest=new aD(this.core,this.logger),this.engine=new iD(this),this.auth=new hD(this.core,this.logger)}static async init(e){const r=new d0(e);return await r.initialize(),r}get context(){return nn(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(),await this.auth.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}}}var p0={exports:{}};(function(t,e){var r=typeof self<"u"?self:jr,n=function(){function o(){this.fetch=!1,this.DOMException=r.DOMException}return o.prototype=r,new o}();(function(o){(function(c){var l={searchParams:"URLSearchParams"in o,iterable:"Symbol"in o&&"iterator"in Symbol,blob:"FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in o,arrayBuffer:"ArrayBuffer"in o};function f(p){return p&&DataView.prototype.isPrototypeOf(p)}if(l.arrayBuffer)var h=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],g=ArrayBuffer.isView||function(p){return p&&h.indexOf(Object.prototype.toString.call(p))>-1};function _(p){if(typeof p!="string"&&(p=String(p)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(p))throw new TypeError("Invalid character in header field name");return p.toLowerCase()}function E(p){return typeof p!="string"&&(p=String(p)),p}function x(p){var b={next:function(){var D=p.shift();return{done:D===void 0,value:D}}};return l.iterable&&(b[Symbol.iterator]=function(){return b}),b}function I(p){this.map={},p instanceof I?p.forEach(function(b,D){this.append(D,b)},this):Array.isArray(p)?p.forEach(function(b){this.append(b[0],b[1])},this):p&&Object.getOwnPropertyNames(p).forEach(function(b){this.append(b,p[b])},this)}I.prototype.append=function(p,b){p=_(p),b=E(b);var D=this.map[p];this.map[p]=D?D+", "+b:b},I.prototype.delete=function(p){delete this.map[_(p)]},I.prototype.get=function(p){return p=_(p),this.has(p)?this.map[p]:null},I.prototype.has=function(p){return this.map.hasOwnProperty(_(p))},I.prototype.set=function(p,b){this.map[_(p)]=E(b)},I.prototype.forEach=function(p,b){for(var D in this.map)this.map.hasOwnProperty(D)&&p.call(b,this.map[D],D,this)},I.prototype.keys=function(){var p=[];return this.forEach(function(b,D){p.push(D)}),x(p)},I.prototype.values=function(){var p=[];return this.forEach(function(b){p.push(b)}),x(p)},I.prototype.entries=function(){var p=[];return this.forEach(function(b,D){p.push([D,b])}),x(p)},l.iterable&&(I.prototype[Symbol.iterator]=I.prototype.entries);function k(p){if(p.bodyUsed)return Promise.reject(new TypeError("Already read"));p.bodyUsed=!0}function W(p){return new Promise(function(b,D){p.onload=function(){b(p.result)},p.onerror=function(){D(p.error)}})}function Y(p){var b=new FileReader,D=W(b);return b.readAsArrayBuffer(p),D}function B(p){var b=new FileReader,D=W(b);return b.readAsText(p),D}function z(p){for(var b=new Uint8Array(p),D=new Array(b.length),O=0;O<b.length;O++)D[O]=String.fromCharCode(b[O]);return D.join("")}function M(p){if(p.slice)return p.slice(0);var b=new Uint8Array(p.byteLength);return b.set(new Uint8Array(p)),b.buffer}function U(){return this.bodyUsed=!1,this._initBody=function(p){this._bodyInit=p,p?typeof p=="string"?this._bodyText=p:l.blob&&Blob.prototype.isPrototypeOf(p)?this._bodyBlob=p:l.formData&&FormData.prototype.isPrototypeOf(p)?this._bodyFormData=p:l.searchParams&&URLSearchParams.prototype.isPrototypeOf(p)?this._bodyText=p.toString():l.arrayBuffer&&l.blob&&f(p)?(this._bodyArrayBuffer=M(p.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):l.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(p)||g(p))?this._bodyArrayBuffer=M(p):this._bodyText=p=Object.prototype.toString.call(p):this._bodyText="",this.headers.get("content-type")||(typeof p=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):l.searchParams&&URLSearchParams.prototype.isPrototypeOf(p)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},l.blob&&(this.blob=function(){var p=k(this);if(p)return p;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?k(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(Y)}),this.text=function(){var p=k(this);if(p)return p;if(this._bodyBlob)return B(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(z(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},l.formData&&(this.formData=function(){return this.text().then(te)}),this.json=function(){return this.text().then(JSON.parse)},this}var F=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function m(p){var b=p.toUpperCase();return F.indexOf(b)>-1?b:p}function $(p,b){b=b||{};var D=b.body;if(p instanceof $){if(p.bodyUsed)throw new TypeError("Already read");this.url=p.url,this.credentials=p.credentials,b.headers||(this.headers=new I(p.headers)),this.method=p.method,this.mode=p.mode,this.signal=p.signal,!D&&p._bodyInit!=null&&(D=p._bodyInit,p.bodyUsed=!0)}else this.url=String(p);if(this.credentials=b.credentials||this.credentials||"same-origin",(b.headers||!this.headers)&&(this.headers=new I(b.headers)),this.method=m(b.method||this.method||"GET"),this.mode=b.mode||this.mode||null,this.signal=b.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&D)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(D)}$.prototype.clone=function(){return new $(this,{body:this._bodyInit})};function te(p){var b=new FormData;return p.trim().split("&").forEach(function(D){if(D){var O=D.split("="),T=O.shift().replace(/\+/g," "),L=O.join("=").replace(/\+/g," ");b.append(decodeURIComponent(T),decodeURIComponent(L))}}),b}function ee(p){var b=new I,D=p.replace(/\r?\n[\t ]+/g," ");return D.split(/\r?\n/).forEach(function(O){var T=O.split(":"),L=T.shift().trim();if(L){var C=T.join(":").trim();b.append(L,C)}}),b}U.call($.prototype);function ne(p,b){b||(b={}),this.type="default",this.status=b.status===void 0?200:b.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in b?b.statusText:"OK",this.headers=new I(b.headers),this.url=b.url||"",this._initBody(p)}U.call(ne.prototype),ne.prototype.clone=function(){return new ne(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new I(this.headers),url:this.url})},ne.error=function(){var p=new ne(null,{status:0,statusText:""});return p.type="error",p};var de=[301,302,303,307,308];ne.redirect=function(p,b){if(de.indexOf(b)===-1)throw new RangeError("Invalid status code");return new ne(null,{status:b,headers:{location:p}})},c.DOMException=o.DOMException;try{new c.DOMException}catch{c.DOMException=function(b,D){this.message=b,this.name=D;var O=Error(b);this.stack=O.stack},c.DOMException.prototype=Object.create(Error.prototype),c.DOMException.prototype.constructor=c.DOMException}function d(p,b){return new Promise(function(D,O){var T=new $(p,b);if(T.signal&&T.signal.aborted)return O(new c.DOMException("Aborted","AbortError"));var L=new XMLHttpRequest;function C(){L.abort()}L.onload=function(){var v={status:L.status,statusText:L.statusText,headers:ee(L.getAllResponseHeaders()||"")};v.url="responseURL"in L?L.responseURL:v.headers.get("X-Request-URL");var N="response"in L?L.response:L.responseText;D(new ne(N,v))},L.onerror=function(){O(new TypeError("Network request failed"))},L.ontimeout=function(){O(new TypeError("Network request failed"))},L.onabort=function(){O(new c.DOMException("Aborted","AbortError"))},L.open(T.method,T.url,!0),T.credentials==="include"?L.withCredentials=!0:T.credentials==="omit"&&(L.withCredentials=!1),"responseType"in L&&l.blob&&(L.responseType="blob"),T.headers.forEach(function(v,N){L.setRequestHeader(N,v)}),T.signal&&(T.signal.addEventListener("abort",C),L.onreadystatechange=function(){L.readyState===4&&T.signal.removeEventListener("abort",C)}),L.send(typeof T._bodyInit>"u"?null:T._bodyInit)})}return d.polyfill=!0,o.fetch||(o.fetch=d,o.Headers=I,o.Request=$,o.Response=ne),c.Headers=I,c.Request=$,c.Response=ne,c.fetch=d,Object.defineProperty(c,"__esModule",{value:!0}),c})({})})(n),n.fetch.ponyfill=!0,delete n.fetch.polyfill;var i=n;e=i.fetch,e.default=i.fetch,e.fetch=i.fetch,e.Headers=i.Headers,e.Request=i.Request,e.Response=i.Response,t.exports=e})(p0,p0.exports);var ow=t3(p0.exports),fD=Object.defineProperty,dD=Object.defineProperties,pD=Object.getOwnPropertyDescriptors,aw=Object.getOwnPropertySymbols,gD=Object.prototype.hasOwnProperty,mD=Object.prototype.propertyIsEnumerable,cw=(t,e,r)=>e in t?fD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,lw=(t,e)=>{for(var r in e||(e={}))gD.call(e,r)&&cw(t,r,e[r]);if(aw)for(var r of aw(e))mD.call(e,r)&&cw(t,r,e[r]);return t},uw=(t,e)=>dD(t,pD(e));const vD={Accept:"application/json","Content-Type":"application/json"},wD="POST",hw={headers:vD,method:wD},fw=10;class fs{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new Dr.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!pv(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=r}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(e){this.isAvailable||await this.register();try{const r=ki(e),n=await(await ow(this.url,uw(lw({},hw),{body:r}))).json();this.onPayload({data:n})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!pv(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",o=>{this.resetMaxListeners(),i(o)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return i(new Error("HTTP connection is missing or invalid"));n()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const r=ki({id:1,jsonrpc:"2.0",method:"test",params:[]});await ow(e,uw(lw({},hw),{body:r}))}this.onOpen()}catch(r){const n=this.parseError(r);throw this.events.emit("register_error",n),this.onClose(),n}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?lc(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),o=Vl(e,i);this.events.emit("payload",o)}parseError(e,r=this.url){return cv(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>fw&&this.events.setMaxListeners(fw)}}const dw="error",yD="wss://relay.walletconnect.com",bD="wc",_D="universal_provider",pw=`${bD}@2:${_D}:`,ED="https://rpc.walletconnect.com/v1/",Ki={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var yc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},g0={exports:{}};/**
|
|
44
44
|
* @license
|
|
45
45
|
* Lodash <https://lodash.com/>
|
|
46
46
|
* Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
|
|
@@ -66,7 +66,7 @@ __p += '`),Dt&&(ge+=`' +
|
|
|
66
66
|
function print() { __p += __j.call(arguments, '') }
|
|
67
67
|
`:`;
|
|
68
68
|
`)+ge+`return __p
|
|
69
|
-
}`;var pt=Zb(function(){return Tt(R,Le+"return "+ge).apply(r,G)});if(pt.source=ge,Op(pt))throw pt;return pt}function _U(s){return Bt(s).toLowerCase()}function EU(s){return Bt(s).toUpperCase()}function AU(s,a,u){if(s=Bt(s),s&&(u||a===r))return ay(s);if(!s||!(a=En(a)))return s;var y=ni(s),S=ni(a),R=cy(y,S),G=ly(y,S)+1;return Ls(y,R,G).join("")}function xU(s,a,u){if(s=Bt(s),s&&(u||a===r))return s.slice(0,hy(s)+1);if(!s||!(a=En(a)))return s;var y=ni(s),S=ly(y,ni(a))+1;return Ls(y,0,S).join("")}function SU(s,a,u){if(s=Bt(s),s&&(u||a===r))return s.replace(Je,"");if(!s||!(a=En(a)))return s;var y=ni(s),S=cy(y,ni(a));return Ls(y,S).join("")}function IU(s,a){var u=ee,y=ne;if(sr(a)){var S="separator"in a?a.separator:S;u="length"in a?ft(a.length):u,y="omission"in a?En(a.omission):y}s=Bt(s);var R=s.length;if(Ca(s)){var G=ni(s);R=G.length}if(u>=R)return s;var Q=u-Oa(y);if(Q<1)return y;var X=G?Ls(G,0,Q).join(""):s.slice(0,Q);if(S===r)return X+y;if(G&&(Q+=X.length-Q),Mp(S)){if(s.slice(Q).search(S)){var ce,ue=X;for(S.global||(S=Wd(S.source,Bt(vt.exec(S))+"g")),S.lastIndex=0;ce=S.exec(ue);)var ge=ce.index;X=X.slice(0,ge===r?Q:ge)}}else if(s.indexOf(En(S),Q)!=Q){var we=X.lastIndexOf(S);we>-1&&(X=X.slice(0,we))}return X+y}function DU(s){return s=Bt(s),s&&Ye.test(s)?s.replace(Ot,rT):s}var CU=La(function(s,a,u){return s+(u?" ":"")+a.toUpperCase()}),Tp=Xy("toUpperCase");function Jb(s,a,u){return s=Bt(s),a=u?r:a,a===r?J$(s)?sT(s):q$(s):s.match(a)||[]}var Zb=gt(function(s,a){try{return Sr(s,r,a)}catch(u){return Op(u)?u:new it(u)}}),OU=es(function(s,a){return jn(a,function(u){u=Ri(u),Zi(s,u,Dp(s[u],s))}),s});function MU(s){var a=s==null?0:s.length,u=qe();return s=a?tr(s,function(y){if(typeof y[1]!="function")throw new kn(c);return[u(y[0]),y[1]]}):[],gt(function(y){for(var S=-1;++S<a;){var R=s[S];if(Sr(R[0],this,y))return Sr(R[1],this,y)}})}function PU(s){return rN(zn(s,_))}function Np(s){return function(){return s}}function $U(s,a){return s==null||s!==s?a:s}var TU=tb(),NU=tb(!0);function dn(s){return s}function Rp(s){return Py(typeof s=="function"?s:zn(s,_))}function RU(s){return Ty(zn(s,_))}function LU(s,a){return Ny(s,zn(a,_))}var BU=gt(function(s,a){return function(u){return Jc(u,s,a)}}),UU=gt(function(s,a){return function(u){return Jc(s,u,a)}});function Lp(s,a,u){var y=Ir(a),S=dh(a,y);u==null&&!(sr(a)&&(S.length||!y.length))&&(u=a,a=s,s=this,S=dh(a,Ir(a)));var R=!(sr(u)&&"chain"in u)||!!u.chain,G=rs(s);return jn(S,function(Q){var X=a[Q];s[Q]=X,G&&(s.prototype[Q]=function(){var ce=this.__chain__;if(R||ce){var ue=s(this.__wrapped__),ge=ue.__actions__=un(this.__actions__);return ge.push({func:X,args:arguments,thisArg:s}),ue.__chain__=ce,ue}return X.apply(s,Ms([this.value()],arguments))})}),s}function FU(){return It._===this&&(It._=hT),this}function Bp(){}function jU(s){return s=ft(s),gt(function(a){return Ry(a,s)})}var kU=pp(tr),qU=pp(ry),zU=pp(Fd);function Xb(s){return _p(s)?jd(Ri(s)):yN(s)}function HU(s){return function(a){return s==null?r:Oo(s,a)}}var KU=nb(),WU=nb(!0);function Up(){return[]}function Fp(){return!1}function VU(){return{}}function GU(){return""}function YU(){return!0}function QU(s,a){if(s=ft(s),s<1||s>T)return[];var u=v,y=Ur(s,v);a=qe(a),s-=v;for(var S=zd(y,a);++u<s;)a(u);return S}function JU(s){return at(s)?tr(s,Ri):An(s)?[s]:un(yb(Bt(s)))}function ZU(s){var a=++lT;return Bt(s)+a}var XU=yh(function(s,a){return s+a},0),eF=gp("ceil"),tF=yh(function(s,a){return s/a},1),rF=gp("floor");function nF(s){return s&&s.length?fh(s,dn,ep):r}function iF(s,a){return s&&s.length?fh(s,qe(a,2),ep):r}function sF(s){return sy(s,dn)}function oF(s,a){return sy(s,qe(a,2))}function aF(s){return s&&s.length?fh(s,dn,ip):r}function cF(s,a){return s&&s.length?fh(s,qe(a,2),ip):r}var lF=yh(function(s,a){return s*a},1),uF=gp("round"),hF=yh(function(s,a){return s-a},0);function fF(s){return s&&s.length?qd(s,dn):0}function dF(s,a){return s&&s.length?qd(s,qe(a,2)):0}return P.after=RL,P.ary=Mb,P.assign=EB,P.assignIn=Hb,P.assignInWith=$h,P.assignWith=AB,P.at=xB,P.before=Pb,P.bind=Dp,P.bindAll=OU,P.bindKey=$b,P.castArray=VL,P.chain=Db,P.chunk=rR,P.compact=nR,P.concat=iR,P.cond=MU,P.conforms=PU,P.constant=Np,P.countBy=fL,P.create=SB,P.curry=Tb,P.curryRight=Nb,P.debounce=Rb,P.defaults=IB,P.defaultsDeep=DB,P.defer=LL,P.delay=BL,P.difference=sR,P.differenceBy=oR,P.differenceWith=aR,P.drop=cR,P.dropRight=lR,P.dropRightWhile=uR,P.dropWhile=hR,P.fill=fR,P.filter=pL,P.flatMap=vL,P.flatMapDeep=wL,P.flatMapDepth=yL,P.flatten=Ab,P.flattenDeep=dR,P.flattenDepth=pR,P.flip=UL,P.flow=TU,P.flowRight=NU,P.fromPairs=gR,P.functions=NB,P.functionsIn=RB,P.groupBy=bL,P.initial=vR,P.intersection=wR,P.intersectionBy=yR,P.intersectionWith=bR,P.invert=BB,P.invertBy=UB,P.invokeMap=EL,P.iteratee=Rp,P.keyBy=AL,P.keys=Ir,P.keysIn=fn,P.map=Ih,P.mapKeys=jB,P.mapValues=kB,P.matches=RU,P.matchesProperty=LU,P.memoize=Ch,P.merge=qB,P.mergeWith=Kb,P.method=BU,P.methodOf=UU,P.mixin=Lp,P.negate=Oh,P.nthArg=jU,P.omit=zB,P.omitBy=HB,P.once=FL,P.orderBy=xL,P.over=kU,P.overArgs=jL,P.overEvery=qU,P.overSome=zU,P.partial=Cp,P.partialRight=Lb,P.partition=SL,P.pick=KB,P.pickBy=Wb,P.property=Xb,P.propertyOf=HU,P.pull=xR,P.pullAll=Sb,P.pullAllBy=SR,P.pullAllWith=IR,P.pullAt=DR,P.range=KU,P.rangeRight=WU,P.rearg=kL,P.reject=CL,P.remove=CR,P.rest=qL,P.reverse=Sp,P.sampleSize=ML,P.set=VB,P.setWith=GB,P.shuffle=PL,P.slice=OR,P.sortBy=NL,P.sortedUniq=LR,P.sortedUniqBy=BR,P.split=vU,P.spread=zL,P.tail=UR,P.take=FR,P.takeRight=jR,P.takeRightWhile=kR,P.takeWhile=qR,P.tap=nL,P.throttle=HL,P.thru=Sh,P.toArray=kb,P.toPairs=Vb,P.toPairsIn=Gb,P.toPath=JU,P.toPlainObject=zb,P.transform=YB,P.unary=KL,P.union=zR,P.unionBy=HR,P.unionWith=KR,P.uniq=WR,P.uniqBy=VR,P.uniqWith=GR,P.unset=QB,P.unzip=Ip,P.unzipWith=Ib,P.update=JB,P.updateWith=ZB,P.values=Fa,P.valuesIn=XB,P.without=YR,P.words=Jb,P.wrap=WL,P.xor=QR,P.xorBy=JR,P.xorWith=ZR,P.zip=XR,P.zipObject=eL,P.zipObjectDeep=tL,P.zipWith=rL,P.entries=Vb,P.entriesIn=Gb,P.extend=Hb,P.extendWith=$h,Lp(P,P),P.add=XU,P.attempt=Zb,P.camelCase=nU,P.capitalize=Yb,P.ceil=eF,P.clamp=eU,P.clone=GL,P.cloneDeep=QL,P.cloneDeepWith=JL,P.cloneWith=YL,P.conformsTo=ZL,P.deburr=Qb,P.defaultTo=$U,P.divide=tF,P.endsWith=iU,P.eq=si,P.escape=sU,P.escapeRegExp=oU,P.every=dL,P.find=gL,P.findIndex=_b,P.findKey=CB,P.findLast=mL,P.findLastIndex=Eb,P.findLastKey=OB,P.floor=rF,P.forEach=Cb,P.forEachRight=Ob,P.forIn=MB,P.forInRight=PB,P.forOwn=$B,P.forOwnRight=TB,P.get=Pp,P.gt=XL,P.gte=eB,P.has=LB,P.hasIn=$p,P.head=xb,P.identity=dn,P.includes=_L,P.indexOf=mR,P.inRange=tU,P.invoke=FB,P.isArguments=$o,P.isArray=at,P.isArrayBuffer=tB,P.isArrayLike=hn,P.isArrayLikeObject=dr,P.isBoolean=rB,P.isBuffer=Bs,P.isDate=nB,P.isElement=iB,P.isEmpty=sB,P.isEqual=oB,P.isEqualWith=aB,P.isError=Op,P.isFinite=cB,P.isFunction=rs,P.isInteger=Bb,P.isLength=Mh,P.isMap=Ub,P.isMatch=lB,P.isMatchWith=uB,P.isNaN=hB,P.isNative=fB,P.isNil=pB,P.isNull=dB,P.isNumber=Fb,P.isObject=sr,P.isObjectLike=cr,P.isPlainObject=nl,P.isRegExp=Mp,P.isSafeInteger=gB,P.isSet=jb,P.isString=Ph,P.isSymbol=An,P.isTypedArray=Ua,P.isUndefined=mB,P.isWeakMap=vB,P.isWeakSet=wB,P.join=_R,P.kebabCase=aU,P.last=Kn,P.lastIndexOf=ER,P.lowerCase=cU,P.lowerFirst=lU,P.lt=yB,P.lte=bB,P.max=nF,P.maxBy=iF,P.mean=sF,P.meanBy=oF,P.min=aF,P.minBy=cF,P.stubArray=Up,P.stubFalse=Fp,P.stubObject=VU,P.stubString=GU,P.stubTrue=YU,P.multiply=lF,P.nth=AR,P.noConflict=FU,P.noop=Bp,P.now=Dh,P.pad=uU,P.padEnd=hU,P.padStart=fU,P.parseInt=dU,P.random=rU,P.reduce=IL,P.reduceRight=DL,P.repeat=pU,P.replace=gU,P.result=WB,P.round=uF,P.runInContext=Z,P.sample=OL,P.size=$L,P.snakeCase=mU,P.some=TL,P.sortedIndex=MR,P.sortedIndexBy=PR,P.sortedIndexOf=$R,P.sortedLastIndex=TR,P.sortedLastIndexBy=NR,P.sortedLastIndexOf=RR,P.startCase=wU,P.startsWith=yU,P.subtract=hF,P.sum=fF,P.sumBy=dF,P.template=bU,P.times=QU,P.toFinite=ns,P.toInteger=ft,P.toLength=qb,P.toLower=_U,P.toNumber=Wn,P.toSafeInteger=_B,P.toString=Bt,P.toUpper=EU,P.trim=AU,P.trimEnd=xU,P.trimStart=SU,P.truncate=IU,P.unescape=DU,P.uniqueId=ZU,P.upperCase=CU,P.upperFirst=Tp,P.each=Cb,P.eachRight=Ob,P.first=xb,Lp(P,function(){var s={};return Ti(P,function(a,u){qt.call(P.prototype,u)||(s[u]=a)}),s}(),{chain:!1}),P.VERSION=n,jn(["bind","bindKey","curry","curryRight","partial","partialRight"],function(s){P[s].placeholder=P}),jn(["drop","take"],function(s,a){At.prototype[s]=function(u){u=u===r?1:br(ft(u),0);var y=this.__filtered__&&!a?new At(this):this.clone();return y.__filtered__?y.__takeCount__=Ur(u,y.__takeCount__):y.__views__.push({size:Ur(u,v),type:s+(y.__dir__<0?"Right":"")}),y},At.prototype[s+"Right"]=function(u){return this.reverse()[s](u).reverse()}}),jn(["filter","map","takeWhile"],function(s,a){var u=a+1,y=u==p||u==D;At.prototype[s]=function(S){var R=this.clone();return R.__iteratees__.push({iteratee:qe(S,3),type:u}),R.__filtered__=R.__filtered__||y,R}}),jn(["head","last"],function(s,a){var u="take"+(a?"Right":"");At.prototype[s]=function(){return this[u](1).value()[0]}}),jn(["initial","tail"],function(s,a){var u="drop"+(a?"":"Right");At.prototype[s]=function(){return this.__filtered__?new At(this):this[u](1)}}),At.prototype.compact=function(){return this.filter(dn)},At.prototype.find=function(s){return this.filter(s).head()},At.prototype.findLast=function(s){return this.reverse().find(s)},At.prototype.invokeMap=gt(function(s,a){return typeof s=="function"?new At(this):this.map(function(u){return Jc(u,s,a)})}),At.prototype.reject=function(s){return this.filter(Oh(qe(s)))},At.prototype.slice=function(s,a){s=ft(s);var u=this;return u.__filtered__&&(s>0||a<0)?new At(u):(s<0?u=u.takeRight(-s):s&&(u=u.drop(s)),a!==r&&(a=ft(a),u=a<0?u.dropRight(-a):u.take(a-s)),u)},At.prototype.takeRightWhile=function(s){return this.reverse().takeWhile(s).reverse()},At.prototype.toArray=function(){return this.take(v)},Ti(At.prototype,function(s,a){var u=/^(?:filter|find|map|reject)|While$/.test(a),y=/^(?:head|last)$/.test(a),S=P[y?"take"+(a=="last"?"Right":""):a],R=y||/^find/.test(a);S&&(P.prototype[a]=function(){var G=this.__wrapped__,Q=y?[1]:arguments,X=G instanceof At,ce=Q[0],ue=X||at(G),ge=function(yt){var Dt=S.apply(P,Ms([yt],Q));return y&&we?Dt[0]:Dt};ue&&u&&typeof ce=="function"&&ce.length!=1&&(X=ue=!1);var we=this.__chain__,Le=!!this.__actions__.length,Ke=R&&!we,pt=X&&!Le;if(!R&&ue){G=pt?G:new At(this);var We=s.apply(G,Q);return We.__actions__.push({func:Sh,args:[ge],thisArg:r}),new qn(We,we)}return Ke&&pt?s.apply(this,Q):(We=this.thru(ge),Ke?y?We.value()[0]:We.value():We)})}),jn(["pop","push","shift","sort","splice","unshift"],function(s){var a=Ju[s],u=/^(?:push|sort|unshift)$/.test(s)?"tap":"thru",y=/^(?:pop|shift)$/.test(s);P.prototype[s]=function(){var S=arguments;if(y&&!this.__chain__){var R=this.value();return a.apply(at(R)?R:[],S)}return this[u](function(G){return a.apply(at(G)?G:[],S)})}}),Ti(At.prototype,function(s,a){var u=P[a];if(u){var y=u.name+"";qt.call(Ta,y)||(Ta[y]=[]),Ta[y].push({name:a,func:u})}}),Ta[wh(r,Y).name]=[{name:"wrapper",func:r}],At.prototype.clone=DT,At.prototype.reverse=CT,At.prototype.value=OT,P.prototype.at=iL,P.prototype.chain=sL,P.prototype.commit=oL,P.prototype.next=aL,P.prototype.plant=lL,P.prototype.reverse=uL,P.prototype.toJSON=P.prototype.valueOf=P.prototype.value=hL,P.prototype.first=P.prototype.head,Hc&&(P.prototype[Hc]=cL),P},Ma=oT();fr?((fr.exports=Ma)._=Ma,Gt._=Ma):It._=Ma}).call(yc)})(g0,g0.exports);var AD=Object.defineProperty,xD=Object.defineProperties,SD=Object.getOwnPropertyDescriptors,gw=Object.getOwnPropertySymbols,ID=Object.prototype.hasOwnProperty,DD=Object.prototype.propertyIsEnumerable,mw=(t,e,r)=>e in t?AD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Zl=(t,e)=>{for(var r in e||(e={}))ID.call(e,r)&&mw(t,r,e[r]);if(gw)for(var r of gw(e))DD.call(e,r)&&mw(t,r,e[r]);return t},CD=(t,e)=>xD(t,SD(e));function ds(t,e,r){var n;const i=ml(t);return((n=e.rpcMap)==null?void 0:n[i.reference])||`${ED}?chainId=${i.namespace}:${i.reference}&projectId=${r}`}function Zs(t){return t.includes(":")?t.split(":")[1]:t}function vw(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function OD(t,e){const r=Object.keys(e.namespaces).filter(i=>i.includes(t));if(!r.length)return[];const n=[];return r.forEach(i=>{const o=e.namespaces[i].accounts;n.push(...o)}),n}function m0(t={},e={}){const r=ww(t),n=ww(e);return g0.exports.merge(r,n)}function ww(t){var e,r,n,i;const o={};if(!oc(t))return o;for(const[c,l]of Object.entries(t)){const f=Tf(c)?[c]:l.chains,h=l.methods||[],g=l.events||[],_=l.rpcMap||{},E=sc(c);o[E]=CD(Zl(Zl({},o[E]),l),{chains:vl(f,(e=o[E])==null?void 0:e.chains),methods:vl(h,(r=o[E])==null?void 0:r.methods),events:vl(g,(n=o[E])==null?void 0:n.events),rpcMap:Zl(Zl({},_),(i=o[E])==null?void 0:i.rpcMap)})}return o}function MD(t){return t.includes(":")?t.split(":")[2]:t}function yw(t){const e={};for(const[r,n]of Object.entries(t)){const i=n.methods||[],o=n.events||[],c=n.accounts||[],l=Tf(r)?[r]:n.chains?n.chains:vw(n.accounts);e[r]={chains:l,methods:i,events:o,accounts:c}}return e}function v0(t){return typeof t=="number"?t:t.includes("0x")?parseInt(t,16):(t=t.includes(":")?t.split(":")[1]:t,isNaN(Number(t))?t:Number(t))}const bw={},er=t=>bw[t],w0=(t,e)=>{bw[t]=e};class PD{constructor(e){this.name="polkadot",this.namespace=e.namespace,this.events=er("events"),this.client=er("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Ki.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=Zs(r);e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||ds(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Hi(new fs(n,er("disableProviderPing")))}}var $D=Object.defineProperty,TD=Object.defineProperties,ND=Object.getOwnPropertyDescriptors,_w=Object.getOwnPropertySymbols,RD=Object.prototype.hasOwnProperty,LD=Object.prototype.propertyIsEnumerable,Ew=(t,e,r)=>e in t?$D(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Aw=(t,e)=>{for(var r in e||(e={}))RD.call(e,r)&&Ew(t,r,e[r]);if(_w)for(var r of _w(e))LD.call(e,r)&&Ew(t,r,e[r]);return t},xw=(t,e)=>TD(t,ND(e));class BD{constructor(e){this.name="eip155",this.namespace=e.namespace,this.events=er("events"),this.client=er("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(parseInt(e),r),this.chainId=parseInt(e),this.events.emit(Ki.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,r){const n=r||ds(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Hi(new fs(n,er("disableProviderPing")))}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=parseInt(Zs(r));e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}async handleSwitchChain(e){var r,n;let i=e.request.params?(r=e.request.params[0])==null?void 0:r.chainId:"0x0";i=i.startsWith("0x")?i:`0x${i}`;const o=parseInt(i,16);if(this.isChainApproved(o))this.setDefaultChain(`${o}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:i}]},chainId:(n=this.namespace.chains)==null?void 0:n[0]}),this.setDefaultChain(`${o}`);else throw new Error(`Failed to switch to chain 'eip155:${o}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var r,n,i;const o=(n=(r=e.request)==null?void 0:r.params)==null?void 0:n[0];if(!o)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const c=this.client.session.get(e.topic),l=((i=c?.sessionProperties)==null?void 0:i.capabilities)||{};if(l!=null&&l[o])return l?.[o];const f=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:xw(Aw({},c.sessionProperties||{}),{capabilities:xw(Aw({},l||{}),{[o]:f})})})}catch(h){console.warn("Failed to update session with capabilities",h)}return f}}class UD{constructor(e){this.name="solana",this.namespace=e.namespace,this.events=er("events"),this.client=er("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Ki.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=Zs(r);e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||ds(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Hi(new fs(n,er("disableProviderPing")))}}class FD{constructor(e){this.name="cosmos",this.namespace=e.namespace,this.events=er("events"),this.client=er("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Ki.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=Zs(r);e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||ds(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Hi(new fs(n,er("disableProviderPing")))}}class jD{constructor(e){this.name="cip34",this.namespace=e.namespace,this.events=er("events"),this.client=er("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Ki.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{const n=this.getCardanoRPCUrl(r),i=Zs(r);e[i]=this.createHttpProvider(i,n)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}getCardanoRPCUrl(e){const r=this.namespace.rpcMap;if(r)return r[e]}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||this.getCardanoRPCUrl(e);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Hi(new fs(n,er("disableProviderPing")))}}class kD{constructor(e){this.name="elrond",this.namespace=e.namespace,this.events=er("events"),this.client=er("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Ki.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=Zs(r);e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||ds(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Hi(new fs(n,er("disableProviderPing")))}}class qD{constructor(e){this.name="multiversx",this.namespace=e.namespace,this.events=er("events"),this.client=er("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Ki.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=Zs(r);e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||ds(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Hi(new fs(n,er("disableProviderPing")))}}class zD{constructor(e){this.name="near",this.namespace=e.namespace,this.events=er("events"),this.client=er("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const n=r||ds(`${this.name}:${e}`,this.namespace);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(Ki.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;e[r]=this.createHttpProvider(r,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||ds(e,this.namespace);return typeof n>"u"?void 0:new Hi(new fs(n,er("disableProviderPing")))}}var HD=Object.defineProperty,KD=Object.defineProperties,WD=Object.getOwnPropertyDescriptors,Sw=Object.getOwnPropertySymbols,VD=Object.prototype.hasOwnProperty,GD=Object.prototype.propertyIsEnumerable,Iw=(t,e,r)=>e in t?HD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Xl=(t,e)=>{for(var r in e||(e={}))VD.call(e,r)&&Iw(t,r,e[r]);if(Sw)for(var r of Sw(e))GD.call(e,r)&&Iw(t,r,e[r]);return t},y0=(t,e)=>KD(t,WD(e));class b0{constructor(e){this.events=new Dr.exports,this.rpcProviders={},this.shouldAbortPairingAttempt=!1,this.maxPairingAttempts=10,this.disableProviderPing=!1,this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:yi(Hl({level:e?.logger||dw})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const r=new b0(e);return await r.initialize(),r}async request(e,r,n){const[i,o]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(i).request({request:Xl({},e),chainId:`${i}:${o}`,topic:this.session.topic,expiry:n})}sendAsync(e,r,n,i){const o=new Date().getTime();this.request(e,n,i).then(c=>r(null,Wl(o,c))).catch(c=>r(c,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:Ut("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:r,response:n}=await this.client.authenticate(e);r&&(this.uri=r,this.events.emit("display_uri",r));const i=await n();if(this.session=i.session,this.session){const o=yw(this.session.namespaces);this.namespaces=m0(this.namespaces,o),this.persist("namespaces",this.namespaces),this.onConnect()}return i}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}removeListener(e,r){this.events.removeListener(e,r)}off(e,r){this.events.off(e,r)}get isWalletConnect(){return!0}async pair(e){this.shouldAbortPairingAttempt=!1;let r=0;do{if(this.shouldAbortPairingAttempt)throw new Error("Pairing aborted");if(r>=this.maxPairingAttempts)throw new Error("Max auto pairing attempts reached");const{uri:n,approval:i}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties});n&&(this.uri=n,this.events.emit("display_uri",n)),await i().then(o=>{this.session=o;const c=yw(o.namespaces);this.namespaces=m0(this.namespaces,c),this.persist("namespaces",this.namespaces)}).catch(o=>{if(o.message!==nw)throw o;r++})}while(!this.session);return this.onConnect(),this.session}setDefaultChain(e,r){try{if(!this.session)return;const[n,i]=this.validateChain(e);this.getProvider(n).setDefaultChain(i,r)}catch(n){if(!/Please call connect/.test(n.message))throw n}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(wi(r)){for(const n of r)e.deletePairings?this.client.core.expirer.set(n.topic,0):await this.client.core.relayer.subscriber.unsubscribe(n.topic);this.logger.info(`Inactive pairings cleared: ${r.length}`)}}abortPairingAttempt(){this.shouldAbortPairingAttempt=!0}async checkStorage(){if(this.namespaces=await this.getFromStore("namespaces"),this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.client.session.length){const e=this.client.session.keys.length-1;this.session=this.client.session.get(this.client.session.keys[e]),this.createProviders()}}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){this.client=this.providerOpts.client||await d0.init({logger:this.providerOpts.logger||dw,relayUrl:this.providerOpts.relayUrl||yD,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name}),this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(r=>sc(r)))];w0("client",this.client),w0("events",this.events),w0("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const n=OD(r,this.session),i=vw(n),o=m0(this.namespaces,this.optionalNamespaces),c=y0(Xl({},o[r]),{accounts:n,chains:i});switch(r){case"eip155":this.rpcProviders[r]=new BD({namespace:c});break;case"solana":this.rpcProviders[r]=new UD({namespace:c});break;case"cosmos":this.rpcProviders[r]=new FD({namespace:c});break;case"polkadot":this.rpcProviders[r]=new PD({namespace:c});break;case"cip34":this.rpcProviders[r]=new jD({namespace:c});break;case"elrond":this.rpcProviders[r]=new kD({namespace:c});break;case"multiversx":this.rpcProviders[r]=new qD({namespace:c});break;case"near":this.rpcProviders[r]=new zD({namespace:c});break}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{const{params:r}=e,{event:n}=r;if(n.name==="accountsChanged"){const i=n.data;i&&wi(i)&&this.events.emit("accountsChanged",i.map(MD))}else if(n.name==="chainChanged"){const i=r.chainId,o=r.event.data,c=sc(i),l=v0(i)!==v0(o)?`${c}:${v0(o)}`:i;this.onChainChanged(l)}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:r})=>{var n;const{namespaces:i}=r,o=(n=this.client)==null?void 0:n.session.get(e);this.session=y0(Xl({},o),{namespaces:i}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:r})}),this.client.on("session_delete",async e=>{await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",y0(Xl({},Ut("USER_DISCONNECTED")),{data:e.topic}))}),this.on(Ki.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){if(!this.rpcProviders[e])throw new Error(`Provider not found: ${e}`);return this.rpcProviders[e]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var r;this.getProvider(e).updateNamespace((r=this.session)==null?void 0:r.namespaces[e])})}setNamespaces(e){const{namespaces:r,optionalNamespaces:n,sessionProperties:i}=e;r&&Object.keys(r).length&&(this.namespaces=r),n&&Object.keys(n).length&&(this.optionalNamespaces=n),this.sessionProperties=i,this.persist("namespaces",r),this.persist("optionalNamespaces",n)}validateChain(e){const[r,n]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[r,n];if(r&&!Object.keys(this.namespaces||{}).map(c=>sc(c)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&n)return[r,n];const i=sc(Object.keys(this.namespaces)[0]),o=this.rpcProviders[i].getDefaultChain();return[i,o]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}onChainChanged(e,r=!1){if(!this.namespaces)return;const[n,i]=this.validateChain(e);i&&(r||this.getProvider(n).setDefaultChain(i),this.namespaces[n]?this.namespaces[n].defaultChain=i:this.namespaces[`${n}:${i}`]?this.namespaces[`${n}:${i}`].defaultChain=i:this.namespaces[`${n}:${i}`]={defaultChain:i},this.persist("namespaces",this.namespaces),this.events.emit("chainChanged",i))}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.session=void 0,this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,this.persist("namespaces",void 0),this.persist("optionalNamespaces",void 0),this.persist("sessionProperties",void 0),await this.cleanupPendingPairings({deletePairings:!0})}persist(e,r){this.client.core.storage.setItem(`${pw}/${e}`,r)}async getFromStore(e){return await this.client.core.storage.getItem(`${pw}/${e}`)}}const YD=b0,QD="wc",JD="ethereum_provider",ZD=`${QD}@2:${JD}:`,XD="https://rpc.walletconnect.com/v1/",eu=["eth_sendTransaction","personal_sign"],Dw=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_sendCalls","wallet_getCapabilities","wallet_getCallsStatus","wallet_showCallsStatus"],tu=["chainChanged","accountsChanged"],Cw=["chainChanged","accountsChanged","message","disconnect","connect"];var eC=Object.defineProperty,tC=Object.defineProperties,rC=Object.getOwnPropertyDescriptors,Ow=Object.getOwnPropertySymbols,nC=Object.prototype.hasOwnProperty,iC=Object.prototype.propertyIsEnumerable,Mw=(t,e,r)=>e in t?eC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,sa=(t,e)=>{for(var r in e||(e={}))nC.call(e,r)&&Mw(t,r,e[r]);if(Ow)for(var r of Ow(e))iC.call(e,r)&&Mw(t,r,e[r]);return t},_0=(t,e)=>tC(t,rC(e));function ru(t){return Number(t[0].split(":")[1])}function nu(t){return`0x${t.toString(16)}`}function sC(t){const{chains:e,optionalChains:r,methods:n,optionalMethods:i,events:o,optionalEvents:c,rpcMap:l}=t;if(!wi(e))throw new Error("Invalid chains");const f={chains:e,methods:n||eu,events:o||tu,rpcMap:sa({},e.length?{[ru(e)]:l[ru(e)]}:{})},h=o?.filter(x=>!tu.includes(x)),g=n?.filter(x=>!eu.includes(x));if(!r&&!c&&!i&&!(h!=null&&h.length)&&!(g!=null&&g.length))return{required:e.length?f:void 0};const _=h?.length&&g?.length||!r,E={chains:[...new Set(_?f.chains.concat(r||[]):r)],methods:[...new Set(f.methods.concat(i!=null&&i.length?i:Dw))],events:[...new Set(f.events.concat(c!=null&&c.length?c:Cw))],rpcMap:l};return{required:e.length?f:void 0,optional:r.length?E:void 0}}class iu{constructor(){this.events=new Dr.exports.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=ZD,this.on=(e,r)=>(this.events.on(e,r),this),this.once=(e,r)=>(this.events.once(e,r),this),this.removeListener=(e,r)=>(this.events.removeListener(e,r),this),this.off=(e,r)=>(this.events.off(e,r),this),this.parseAccount=e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e,this.signer={},this.rpc={}}static async init(e){const r=new iu;return await r.initialize(e),r}async request(e,r){return await this.signer.request(e,this.formatChainId(this.chainId),r)}sendAsync(e,r,n){this.signer.sendAsync(e,r,this.formatChainId(this.chainId),n)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:r,optional:n}=sC(this.rpc);try{const i=await new Promise(async(c,l)=>{var f;this.rpc.showQrModal&&((f=this.modal)==null||f.subscribeModal(h=>{!h.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),l(new Error("Connection request reset. Please try again.")))})),await this.signer.connect(_0(sa({namespaces:sa({},r&&{[this.namespace]:r})},n&&{optionalNamespaces:{[this.namespace]:n}}),{pairingTopic:e?.pairingTopic})).then(h=>{c(h)}).catch(h=>{l(new Error(h.message))})});if(!i)return;const o=Y1(i.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:nu(this.chainId)})}catch(i){throw this.signer.logger.error(i),i}finally{this.modal&&this.modal.closeModal()}}async authenticate(e){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e?.chains});try{const r=await new Promise(async(i,o)=>{var c;this.rpc.showQrModal&&((c=this.modal)==null||c.subscribeModal(l=>{!l.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),o(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(_0(sa({},e),{chains:this.rpc.chains})).then(l=>{i(l)}).catch(l=>{o(new Error(l.message))})}),n=r.session;if(n){const i=Y1(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:i),this.setAccounts(i),this.events.emit("connect",{chainId:nu(this.chainId)})}return r}catch(r){throw this.signer.logger.error(r),r}finally{this.modal&&this.modal.closeModal()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:r}=e,{event:n}=r;n.name==="accountsChanged"?(this.accounts=this.parseAccounts(n.data),this.events.emit("accountsChanged",this.accounts)):n.name==="chainChanged"?this.setChainId(this.formatChainId(n.data)):this.events.emit(n.name,n.data),this.events.emit("session_event",e)}),this.signer.on("chainChanged",e=>{const r=parseInt(e);this.chainId=r,this.events.emit("chainChanged",nu(this.chainId)),this.persist()}),this.signer.on("session_update",e=>{this.events.emit("session_update",e)}),this.signer.on("session_delete",e=>{this.reset(),this.events.emit("session_delete",e),this.events.emit("disconnect",_0(sa({},Ut("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{var r,n;this.rpc.showQrModal&&((r=this.modal)==null||r.closeModal(),(n=this.modal)==null||n.openModal({uri:e})),this.events.emit("display_uri",e)})}switchEthereumChain(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const r=e.filter(n=>this.isCompatibleChainId(n)).map(n=>this.parseChainId(n));r.length&&(this.chainId=r[0],this.events.emit("chainChanged",nu(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const r=this.parseChainId(e);this.chainId=r,this.switchEthereumChain(r)}}parseAccountId(e){const[r,n,i]=e.split(":");return{chainId:`${r}:${n}`,address:i}}setAccounts(e){this.accounts=e.filter(r=>this.parseChainId(this.parseAccountId(r).chainId)===this.chainId).map(r=>this.parseAccountId(r).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var r,n;const i=(r=e?.chains)!=null?r:[],o=(n=e?.optionalChains)!=null?n:[],c=i.concat(o);if(!c.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const l=i.length?e?.methods||eu:[],f=i.length?e?.events||tu:[],h=e?.optionalMethods||[],g=e?.optionalEvents||[],_=e?.rpcMap||this.buildRpcMap(c,e.projectId),E=e?.qrModalOptions||void 0;return{chains:i?.map(x=>this.formatChainId(x)),optionalChains:o.map(x=>this.formatChainId(x)),methods:l,events:f,optionalMethods:h,optionalEvents:g,rpcMap:_,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:E,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,r){const n={};return e.forEach(i=>{n[i]=this.getRpcUrl(i,r)}),n}async initialize(e){this.rpc=this.getRpcConfig(e);const r=this.rpc.metadata;if(r===void 0)throw new Error("Metadata field is required");if(this.chainId=this.rpc.chains.length?ru(this.rpc.chains):ru(this.rpc.optionalChains),this.signer=await YD.init({projectId:this.rpc.projectId,metadata:r,disableProviderPing:e.disableProviderPing,relayUrl:e.relayUrl,storageOptions:e.storageOptions}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let n;try{const{WalletConnectModal:i}=await Promise.resolve().then(function(){return CC});n=i}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(n)try{this.modal=new n(sa({projectId:this.rpc.projectId},this.rpc.qrModalOptions))}catch(i){throw this.signer.logger.error(i),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:n,rpcMap:i}=e;r&&wi(r)&&(this.rpc.chains=r.map(o=>this.formatChainId(o)),r.forEach(o=>{this.rpc.rpcMap[o]=i?.[o]||this.getRpcUrl(o)})),n&&wi(n)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=n?.map(o=>this.formatChainId(o)),n.forEach(o=>{this.rpc.rpcMap[o]=i?.[o]||this.getRpcUrl(o)}))}getRpcUrl(e,r){var n;return((n=this.rpc.rpcMap)==null?void 0:n[e])||`${XD}?chainId=eip155:${e}&projectId=${r||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),r=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:r?.accounts),this.setAccounts(r?.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(r=>this.signer.logger.warn(r))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return typeof e=="string"||e instanceof String?[this.parseAccount(e)]:e.map(r=>this.parseAccount(r))}}const oC=iu,aC=Symbol(),Pw=Object.getPrototypeOf,E0=new WeakMap,cC=t=>t&&(E0.has(t)?E0.get(t):Pw(t)===Object.prototype||Pw(t)===Array.prototype),lC=t=>cC(t)&&t[aC]||null,$w=(t,e=!0)=>{E0.set(t,e)},A0=t=>typeof t=="object"&&t!==null,ps=new WeakMap,su=new WeakSet,uC=(t=Object.is,e=(h,g)=>new Proxy(h,g),r=h=>A0(h)&&!su.has(h)&&(Array.isArray(h)||!(Symbol.iterator in h))&&!(h instanceof WeakMap)&&!(h instanceof WeakSet)&&!(h instanceof Error)&&!(h instanceof Number)&&!(h instanceof Date)&&!(h instanceof String)&&!(h instanceof RegExp)&&!(h instanceof ArrayBuffer),n=h=>{switch(h.status){case"fulfilled":return h.value;case"rejected":throw h.reason;default:throw h}},i=new WeakMap,o=(h,g,_=n)=>{const E=i.get(h);if(E?.[0]===g)return E[1];const x=Array.isArray(h)?[]:Object.create(Object.getPrototypeOf(h));return $w(x,!0),i.set(h,[g,x]),Reflect.ownKeys(h).forEach(I=>{if(Object.getOwnPropertyDescriptor(x,I))return;const k=Reflect.get(h,I),W={value:k,enumerable:!0,configurable:!0};if(su.has(k))$w(k,!1);else if(k instanceof Promise)delete W.value,W.get=()=>_(k);else if(ps.has(k)){const[Y,B]=ps.get(k);W.value=o(Y,B(),_)}Object.defineProperty(x,I,W)}),Object.preventExtensions(x)},c=new WeakMap,l=[1,1],f=h=>{if(!A0(h))throw new Error("object required");const g=c.get(h);if(g)return g;let _=l[0];const E=new Set,x=(te,ee=++l[0])=>{_!==ee&&(_=ee,E.forEach(ne=>ne(te,ee)))};let I=l[1];const k=(te=++l[1])=>(I!==te&&!E.size&&(I=te,Y.forEach(([ee])=>{const ne=ee[1](te);ne>_&&(_=ne)})),_),W=te=>(ee,ne)=>{const de=[...ee];de[1]=[te,...de[1]],x(de,ne)},Y=new Map,B=(te,ee)=>{if(Y.has(te))throw new Error("prop listener already exists");if(E.size){const ne=ee[3](W(te));Y.set(te,[ee,ne])}else Y.set(te,[ee])},z=te=>{var ee;const ne=Y.get(te);ne&&(Y.delete(te),(ee=ne[1])==null||ee.call(ne))},M=te=>(E.add(te),E.size===1&&Y.forEach(([ne,de],d)=>{if(de)throw new Error("remove already exists");const p=ne[3](W(d));Y.set(d,[ne,p])}),()=>{E.delete(te),E.size===0&&Y.forEach(([ne,de],d)=>{de&&(de(),Y.set(d,[ne]))})}),U=Array.isArray(h)?[]:Object.create(Object.getPrototypeOf(h)),m=e(U,{deleteProperty(te,ee){const ne=Reflect.get(te,ee);z(ee);const de=Reflect.deleteProperty(te,ee);return de&&x(["delete",[ee],ne]),de},set(te,ee,ne,de){const d=Reflect.has(te,ee),p=Reflect.get(te,ee,de);if(d&&(t(p,ne)||c.has(ne)&&t(p,c.get(ne))))return!0;z(ee),A0(ne)&&(ne=lC(ne)||ne);let b=ne;if(ne instanceof Promise)ne.then(D=>{ne.status="fulfilled",ne.value=D,x(["resolve",[ee],D])}).catch(D=>{ne.status="rejected",ne.reason=D,x(["reject",[ee],D])});else{!ps.has(ne)&&r(ne)&&(b=f(ne));const D=!su.has(b)&&ps.get(b);D&&B(ee,D)}return Reflect.set(te,ee,b,de),x(["set",[ee],ne,p]),!0}});c.set(h,m);const $=[U,k,o,M];return ps.set(m,$),Reflect.ownKeys(h).forEach(te=>{const ee=Object.getOwnPropertyDescriptor(h,te);"value"in ee&&(m[te]=h[te],delete ee.value,delete ee.writable),Object.defineProperty(U,te,ee)}),m})=>[f,ps,su,t,e,r,n,i,o,c,l],[hC]=uC();function gs(t={}){return hC(t)}function Xs(t,e,r){const n=ps.get(t);n||console.warn("Please use proxy object");let i;const o=[],c=n[3];let l=!1;const h=c(g=>{if(o.push(g),r){e(o.splice(0));return}i||(i=Promise.resolve().then(()=>{i=void 0,l&&e(o.splice(0))}))});return l=!0,()=>{l=!1,h()}}function fC(t,e){const r=ps.get(t);r||console.warn("Please use proxy object");const[n,i,o]=r;return o(n,i(),e)}const Ar=gs({history:["ConnectWallet"],view:"ConnectWallet",data:void 0}),rr={state:Ar,subscribe(t){return Xs(Ar,()=>t(Ar))},push(t,e){t!==Ar.view&&(Ar.view=t,e&&(Ar.data=e),Ar.history.push(t))},reset(t){Ar.view=t,Ar.history=[t]},replace(t){Ar.history.length>1&&(Ar.history[Ar.history.length-1]=t,Ar.view=t)},goBack(){if(Ar.history.length>1){Ar.history.pop();const[t]=Ar.history.slice(-1);Ar.view=t}},setData(t){Ar.data=t}},Ue={WALLETCONNECT_DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",WCM_VERSION:"WCM_VERSION",RECOMMENDED_WALLET_AMOUNT:9,isMobile(){return typeof window<"u"?!!(window.matchMedia("(pointer:coarse)").matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},isAndroid(){return Ue.isMobile()&&navigator.userAgent.toLowerCase().includes("android")},isIos(){const t=navigator.userAgent.toLowerCase();return Ue.isMobile()&&(t.includes("iphone")||t.includes("ipad"))},isHttpUrl(t){return t.startsWith("http://")||t.startsWith("https://")},isArray(t){return Array.isArray(t)&&t.length>0},formatNativeUrl(t,e,r){if(Ue.isHttpUrl(t))return this.formatUniversalUrl(t,e,r);let n=t;n.includes("://")||(n=t.replaceAll("/","").replaceAll(":",""),n=`${n}://`),n.endsWith("/")||(n=`${n}/`),this.setWalletConnectDeepLink(n,r);const i=encodeURIComponent(e);return`${n}wc?uri=${i}`},formatUniversalUrl(t,e,r){if(!Ue.isHttpUrl(t))return this.formatNativeUrl(t,e,r);let n=t;n.endsWith("/")||(n=`${n}/`),this.setWalletConnectDeepLink(n,r);const i=encodeURIComponent(e);return`${n}wc?uri=${i}`},async wait(t){return new Promise(e=>{setTimeout(e,t)})},openHref(t,e){window.open(t,e,"noreferrer noopener")},setWalletConnectDeepLink(t,e){try{localStorage.setItem(Ue.WALLETCONNECT_DEEPLINK_CHOICE,JSON.stringify({href:t,name:e}))}catch{console.info("Unable to set WalletConnect deep link")}},setWalletConnectAndroidDeepLink(t){try{const[e]=t.split("?");localStorage.setItem(Ue.WALLETCONNECT_DEEPLINK_CHOICE,JSON.stringify({href:e,name:"Android"}))}catch{console.info("Unable to set WalletConnect android deep link")}},removeWalletConnectDeepLink(){try{localStorage.removeItem(Ue.WALLETCONNECT_DEEPLINK_CHOICE)}catch{console.info("Unable to remove WalletConnect deep link")}},setModalVersionInStorage(){try{typeof localStorage<"u"&&localStorage.setItem(Ue.WCM_VERSION,"2.6.2")}catch{console.info("Unable to set Web3Modal version in storage")}},getWalletRouterData(){var t;const e=(t=rr.state.data)==null?void 0:t.Wallet;if(!e)throw new Error('Missing "Wallet" view data');return e}},dC=typeof location<"u"&&(location.hostname.includes("localhost")||location.protocol.includes("https")),Br=gs({enabled:dC,userSessionId:"",events:[],connectedWalletId:void 0}),Tw={state:Br,subscribe(t){return Xs(Br.events,()=>t(fC(Br.events[Br.events.length-1])))},initialize(){Br.enabled&&typeof(crypto==null?void 0:crypto.randomUUID)<"u"&&(Br.userSessionId=crypto.randomUUID())},setConnectedWalletId(t){Br.connectedWalletId=t},click(t){if(Br.enabled){const e={type:"CLICK",name:t.name,userSessionId:Br.userSessionId,timestamp:Date.now(),data:t};Br.events.push(e)}},track(t){if(Br.enabled){const e={type:"TRACK",name:t.name,userSessionId:Br.userSessionId,timestamp:Date.now(),data:t};Br.events.push(e)}},view(t){if(Br.enabled){const e={type:"VIEW",name:t.name,userSessionId:Br.userSessionId,timestamp:Date.now(),data:t};Br.events.push(e)}}},xi=gs({chains:void 0,walletConnectUri:void 0,isAuth:!1,isCustomDesktop:!1,isCustomMobile:!1,isDataLoaded:!1,isUiLoaded:!1}),hr={state:xi,subscribe(t){return Xs(xi,()=>t(xi))},setChains(t){xi.chains=t},setWalletConnectUri(t){xi.walletConnectUri=t},setIsCustomDesktop(t){xi.isCustomDesktop=t},setIsCustomMobile(t){xi.isCustomMobile=t},setIsDataLoaded(t){xi.isDataLoaded=t},setIsUiLoaded(t){xi.isUiLoaded=t},setIsAuth(t){xi.isAuth=t}},ou=gs({projectId:"",mobileWallets:void 0,desktopWallets:void 0,walletImages:void 0,chains:void 0,enableAuthMode:!1,enableExplorer:!0,explorerExcludedWalletIds:void 0,explorerRecommendedWalletIds:void 0,termsOfServiceUrl:void 0,privacyPolicyUrl:void 0}),wn={state:ou,subscribe(t){return Xs(ou,()=>t(ou))},setConfig(t){var e,r;Tw.initialize(),hr.setChains(t.chains),hr.setIsAuth(!!t.enableAuthMode),hr.setIsCustomMobile(!!((e=t.mobileWallets)!=null&&e.length)),hr.setIsCustomDesktop(!!((r=t.desktopWallets)!=null&&r.length)),Ue.setModalVersionInStorage(),Object.assign(ou,t)}};var pC=Object.defineProperty,Nw=Object.getOwnPropertySymbols,gC=Object.prototype.hasOwnProperty,mC=Object.prototype.propertyIsEnumerable,Rw=(t,e,r)=>e in t?pC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,vC=(t,e)=>{for(var r in e||(e={}))gC.call(e,r)&&Rw(t,r,e[r]);if(Nw)for(var r of Nw(e))mC.call(e,r)&&Rw(t,r,e[r]);return t};const x0="https://explorer-api.walletconnect.com",S0="wcm",I0="js-2.6.2";async function au(t,e){const r=vC({sdkType:S0,sdkVersion:I0},e),n=new URL(t,x0);return n.searchParams.append("projectId",wn.state.projectId),Object.entries(r).forEach(([i,o])=>{o&&n.searchParams.append(i,String(o))}),(await fetch(n)).json()}const eo={async getDesktopListings(t){return au("/w3m/v1/getDesktopListings",t)},async getMobileListings(t){return au("/w3m/v1/getMobileListings",t)},async getInjectedListings(t){return au("/w3m/v1/getInjectedListings",t)},async getAllListings(t){return au("/w3m/v1/getAllListings",t)},getWalletImageUrl(t){return`${x0}/w3m/v1/getWalletImage/${t}?projectId=${wn.state.projectId}&sdkType=${S0}&sdkVersion=${I0}`},getAssetImageUrl(t){return`${x0}/w3m/v1/getAssetImage/${t}?projectId=${wn.state.projectId}&sdkType=${S0}&sdkVersion=${I0}`}};var wC=Object.defineProperty,Lw=Object.getOwnPropertySymbols,yC=Object.prototype.hasOwnProperty,bC=Object.prototype.propertyIsEnumerable,Bw=(t,e,r)=>e in t?wC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,_C=(t,e)=>{for(var r in e||(e={}))yC.call(e,r)&&Bw(t,r,e[r]);if(Lw)for(var r of Lw(e))bC.call(e,r)&&Bw(t,r,e[r]);return t};const Uw=Ue.isMobile(),Si=gs({wallets:{listings:[],total:0,page:1},search:{listings:[],total:0,page:1},recomendedWallets:[]}),an={state:Si,async getRecomendedWallets(){const{explorerRecommendedWalletIds:t,explorerExcludedWalletIds:e}=wn.state;if(t==="NONE"||e==="ALL"&&!t)return Si.recomendedWallets;if(Ue.isArray(t)){const r={recommendedIds:t.join(",")},{listings:n}=await eo.getAllListings(r),i=Object.values(n);i.sort((o,c)=>{const l=t.indexOf(o.id),f=t.indexOf(c.id);return l-f}),Si.recomendedWallets=i}else{const{chains:r,isAuth:n}=hr.state,i=r?.join(","),o=Ue.isArray(e),c={page:1,sdks:n?"auth_v1":void 0,entries:Ue.RECOMMENDED_WALLET_AMOUNT,chains:i,version:2,excludedIds:o?e.join(","):void 0},{listings:l}=Uw?await eo.getMobileListings(c):await eo.getDesktopListings(c);Si.recomendedWallets=Object.values(l)}return Si.recomendedWallets},async getWallets(t){const e=_C({},t),{explorerRecommendedWalletIds:r,explorerExcludedWalletIds:n}=wn.state,{recomendedWallets:i}=Si;if(n==="ALL")return Si.wallets;i.length?e.excludedIds=i.map(_=>_.id).join(","):Ue.isArray(r)&&(e.excludedIds=r.join(",")),Ue.isArray(n)&&(e.excludedIds=[e.excludedIds,n].filter(Boolean).join(",")),hr.state.isAuth&&(e.sdks="auth_v1");const{page:o,search:c}=t,{listings:l,total:f}=Uw?await eo.getMobileListings(e):await eo.getDesktopListings(e),h=Object.values(l),g=c?"search":"wallets";return Si[g]={listings:[...Si[g].listings,...h],total:f,page:o??1},{listings:h,total:f}},getWalletImageUrl(t){return eo.getWalletImageUrl(t)},getAssetImageUrl(t){return eo.getAssetImageUrl(t)},resetSearch(){Si.search={listings:[],total:0,page:1}}},oa=gs({open:!1}),to={state:oa,subscribe(t){return Xs(oa,()=>t(oa))},async open(t){return new Promise(e=>{const{isUiLoaded:r,isDataLoaded:n}=hr.state;if(Ue.removeWalletConnectDeepLink(),hr.setWalletConnectUri(t?.uri),hr.setChains(t?.chains),rr.reset("ConnectWallet"),r&&n)oa.open=!0,e();else{const i=setInterval(()=>{const o=hr.state;o.isUiLoaded&&o.isDataLoaded&&(clearInterval(i),oa.open=!0,e())},200)}})},close(){oa.open=!1}};var EC=Object.defineProperty,Fw=Object.getOwnPropertySymbols,AC=Object.prototype.hasOwnProperty,xC=Object.prototype.propertyIsEnumerable,jw=(t,e,r)=>e in t?EC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,SC=(t,e)=>{for(var r in e||(e={}))AC.call(e,r)&&jw(t,r,e[r]);if(Fw)for(var r of Fw(e))xC.call(e,r)&&jw(t,r,e[r]);return t};function IC(){return typeof matchMedia<"u"&&matchMedia("(prefers-color-scheme: dark)").matches}const bc=gs({themeMode:IC()?"dark":"light"}),ms={state:bc,subscribe(t){return Xs(bc,()=>t(bc))},setThemeConfig(t){const{themeMode:e,themeVariables:r}=t;e&&(bc.themeMode=e),r&&(bc.themeVariables=SC({},r))}},ro=gs({open:!1,message:"",variant:"success"}),vs={state:ro,subscribe(t){return Xs(ro,()=>t(ro))},openToast(t,e){ro.open=!0,ro.message=t,ro.variant=e},closeToast(){ro.open=!1}};class DC{constructor(e){this.openModal=to.open,this.closeModal=to.close,this.subscribeModal=to.subscribe,this.setTheme=ms.setThemeConfig,ms.setThemeConfig(e),wn.setConfig(e),this.initUi()}async initUi(){if(typeof window<"u"){await Promise.resolve().then(function(){return L$});const e=document.createElement("wcm-modal");document.body.insertAdjacentElement("beforeend",e),hr.setIsUiLoaded(!0)}}}var CC=Object.freeze({__proto__:null,WalletConnectModal:DC});/**
|
|
69
|
+
}`;var pt=Zb(function(){return Tt(R,Le+"return "+ge).apply(r,G)});if(pt.source=ge,Op(pt))throw pt;return pt}function _U(s){return Bt(s).toLowerCase()}function EU(s){return Bt(s).toUpperCase()}function AU(s,a,u){if(s=Bt(s),s&&(u||a===r))return ay(s);if(!s||!(a=En(a)))return s;var y=ni(s),S=ni(a),R=cy(y,S),G=ly(y,S)+1;return Ls(y,R,G).join("")}function xU(s,a,u){if(s=Bt(s),s&&(u||a===r))return s.slice(0,hy(s)+1);if(!s||!(a=En(a)))return s;var y=ni(s),S=ly(y,ni(a))+1;return Ls(y,0,S).join("")}function SU(s,a,u){if(s=Bt(s),s&&(u||a===r))return s.replace(Je,"");if(!s||!(a=En(a)))return s;var y=ni(s),S=cy(y,ni(a));return Ls(y,S).join("")}function IU(s,a){var u=ee,y=ne;if(sr(a)){var S="separator"in a?a.separator:S;u="length"in a?ft(a.length):u,y="omission"in a?En(a.omission):y}s=Bt(s);var R=s.length;if(Ca(s)){var G=ni(s);R=G.length}if(u>=R)return s;var Q=u-Oa(y);if(Q<1)return y;var X=G?Ls(G,0,Q).join(""):s.slice(0,Q);if(S===r)return X+y;if(G&&(Q+=X.length-Q),Mp(S)){if(s.slice(Q).search(S)){var ce,ue=X;for(S.global||(S=Wd(S.source,Bt(vt.exec(S))+"g")),S.lastIndex=0;ce=S.exec(ue);)var ge=ce.index;X=X.slice(0,ge===r?Q:ge)}}else if(s.indexOf(En(S),Q)!=Q){var we=X.lastIndexOf(S);we>-1&&(X=X.slice(0,we))}return X+y}function DU(s){return s=Bt(s),s&&Ye.test(s)?s.replace(Ot,rT):s}var CU=La(function(s,a,u){return s+(u?" ":"")+a.toUpperCase()}),Tp=Xy("toUpperCase");function Jb(s,a,u){return s=Bt(s),a=u?r:a,a===r?J$(s)?sT(s):q$(s):s.match(a)||[]}var Zb=gt(function(s,a){try{return Sr(s,r,a)}catch(u){return Op(u)?u:new it(u)}}),OU=es(function(s,a){return jn(a,function(u){u=Ri(u),Zi(s,u,Dp(s[u],s))}),s});function MU(s){var a=s==null?0:s.length,u=qe();return s=a?tr(s,function(y){if(typeof y[1]!="function")throw new kn(c);return[u(y[0]),y[1]]}):[],gt(function(y){for(var S=-1;++S<a;){var R=s[S];if(Sr(R[0],this,y))return Sr(R[1],this,y)}})}function PU(s){return rN(zn(s,_))}function Np(s){return function(){return s}}function $U(s,a){return s==null||s!==s?a:s}var TU=tb(),NU=tb(!0);function dn(s){return s}function Rp(s){return Py(typeof s=="function"?s:zn(s,_))}function RU(s){return Ty(zn(s,_))}function LU(s,a){return Ny(s,zn(a,_))}var BU=gt(function(s,a){return function(u){return Jc(u,s,a)}}),UU=gt(function(s,a){return function(u){return Jc(s,u,a)}});function Lp(s,a,u){var y=Ir(a),S=dh(a,y);u==null&&!(sr(a)&&(S.length||!y.length))&&(u=a,a=s,s=this,S=dh(a,Ir(a)));var R=!(sr(u)&&"chain"in u)||!!u.chain,G=rs(s);return jn(S,function(Q){var X=a[Q];s[Q]=X,G&&(s.prototype[Q]=function(){var ce=this.__chain__;if(R||ce){var ue=s(this.__wrapped__),ge=ue.__actions__=un(this.__actions__);return ge.push({func:X,args:arguments,thisArg:s}),ue.__chain__=ce,ue}return X.apply(s,Ms([this.value()],arguments))})}),s}function FU(){return It._===this&&(It._=hT),this}function Bp(){}function jU(s){return s=ft(s),gt(function(a){return Ry(a,s)})}var kU=pp(tr),qU=pp(ry),zU=pp(Fd);function Xb(s){return _p(s)?jd(Ri(s)):yN(s)}function HU(s){return function(a){return s==null?r:Oo(s,a)}}var KU=nb(),WU=nb(!0);function Up(){return[]}function Fp(){return!1}function VU(){return{}}function GU(){return""}function YU(){return!0}function QU(s,a){if(s=ft(s),s<1||s>T)return[];var u=v,y=Ur(s,v);a=qe(a),s-=v;for(var S=zd(y,a);++u<s;)a(u);return S}function JU(s){return at(s)?tr(s,Ri):An(s)?[s]:un(yb(Bt(s)))}function ZU(s){var a=++lT;return Bt(s)+a}var XU=yh(function(s,a){return s+a},0),eF=gp("ceil"),tF=yh(function(s,a){return s/a},1),rF=gp("floor");function nF(s){return s&&s.length?fh(s,dn,ep):r}function iF(s,a){return s&&s.length?fh(s,qe(a,2),ep):r}function sF(s){return sy(s,dn)}function oF(s,a){return sy(s,qe(a,2))}function aF(s){return s&&s.length?fh(s,dn,ip):r}function cF(s,a){return s&&s.length?fh(s,qe(a,2),ip):r}var lF=yh(function(s,a){return s*a},1),uF=gp("round"),hF=yh(function(s,a){return s-a},0);function fF(s){return s&&s.length?qd(s,dn):0}function dF(s,a){return s&&s.length?qd(s,qe(a,2)):0}return P.after=RL,P.ary=Mb,P.assign=EB,P.assignIn=Hb,P.assignInWith=$h,P.assignWith=AB,P.at=xB,P.before=Pb,P.bind=Dp,P.bindAll=OU,P.bindKey=$b,P.castArray=VL,P.chain=Db,P.chunk=rR,P.compact=nR,P.concat=iR,P.cond=MU,P.conforms=PU,P.constant=Np,P.countBy=fL,P.create=SB,P.curry=Tb,P.curryRight=Nb,P.debounce=Rb,P.defaults=IB,P.defaultsDeep=DB,P.defer=LL,P.delay=BL,P.difference=sR,P.differenceBy=oR,P.differenceWith=aR,P.drop=cR,P.dropRight=lR,P.dropRightWhile=uR,P.dropWhile=hR,P.fill=fR,P.filter=pL,P.flatMap=vL,P.flatMapDeep=wL,P.flatMapDepth=yL,P.flatten=Ab,P.flattenDeep=dR,P.flattenDepth=pR,P.flip=UL,P.flow=TU,P.flowRight=NU,P.fromPairs=gR,P.functions=NB,P.functionsIn=RB,P.groupBy=bL,P.initial=vR,P.intersection=wR,P.intersectionBy=yR,P.intersectionWith=bR,P.invert=BB,P.invertBy=UB,P.invokeMap=EL,P.iteratee=Rp,P.keyBy=AL,P.keys=Ir,P.keysIn=fn,P.map=Ih,P.mapKeys=jB,P.mapValues=kB,P.matches=RU,P.matchesProperty=LU,P.memoize=Ch,P.merge=qB,P.mergeWith=Kb,P.method=BU,P.methodOf=UU,P.mixin=Lp,P.negate=Oh,P.nthArg=jU,P.omit=zB,P.omitBy=HB,P.once=FL,P.orderBy=xL,P.over=kU,P.overArgs=jL,P.overEvery=qU,P.overSome=zU,P.partial=Cp,P.partialRight=Lb,P.partition=SL,P.pick=KB,P.pickBy=Wb,P.property=Xb,P.propertyOf=HU,P.pull=xR,P.pullAll=Sb,P.pullAllBy=SR,P.pullAllWith=IR,P.pullAt=DR,P.range=KU,P.rangeRight=WU,P.rearg=kL,P.reject=CL,P.remove=CR,P.rest=qL,P.reverse=Sp,P.sampleSize=ML,P.set=VB,P.setWith=GB,P.shuffle=PL,P.slice=OR,P.sortBy=NL,P.sortedUniq=LR,P.sortedUniqBy=BR,P.split=vU,P.spread=zL,P.tail=UR,P.take=FR,P.takeRight=jR,P.takeRightWhile=kR,P.takeWhile=qR,P.tap=nL,P.throttle=HL,P.thru=Sh,P.toArray=kb,P.toPairs=Vb,P.toPairsIn=Gb,P.toPath=JU,P.toPlainObject=zb,P.transform=YB,P.unary=KL,P.union=zR,P.unionBy=HR,P.unionWith=KR,P.uniq=WR,P.uniqBy=VR,P.uniqWith=GR,P.unset=QB,P.unzip=Ip,P.unzipWith=Ib,P.update=JB,P.updateWith=ZB,P.values=Fa,P.valuesIn=XB,P.without=YR,P.words=Jb,P.wrap=WL,P.xor=QR,P.xorBy=JR,P.xorWith=ZR,P.zip=XR,P.zipObject=eL,P.zipObjectDeep=tL,P.zipWith=rL,P.entries=Vb,P.entriesIn=Gb,P.extend=Hb,P.extendWith=$h,Lp(P,P),P.add=XU,P.attempt=Zb,P.camelCase=nU,P.capitalize=Yb,P.ceil=eF,P.clamp=eU,P.clone=GL,P.cloneDeep=QL,P.cloneDeepWith=JL,P.cloneWith=YL,P.conformsTo=ZL,P.deburr=Qb,P.defaultTo=$U,P.divide=tF,P.endsWith=iU,P.eq=si,P.escape=sU,P.escapeRegExp=oU,P.every=dL,P.find=gL,P.findIndex=_b,P.findKey=CB,P.findLast=mL,P.findLastIndex=Eb,P.findLastKey=OB,P.floor=rF,P.forEach=Cb,P.forEachRight=Ob,P.forIn=MB,P.forInRight=PB,P.forOwn=$B,P.forOwnRight=TB,P.get=Pp,P.gt=XL,P.gte=eB,P.has=LB,P.hasIn=$p,P.head=xb,P.identity=dn,P.includes=_L,P.indexOf=mR,P.inRange=tU,P.invoke=FB,P.isArguments=$o,P.isArray=at,P.isArrayBuffer=tB,P.isArrayLike=hn,P.isArrayLikeObject=dr,P.isBoolean=rB,P.isBuffer=Bs,P.isDate=nB,P.isElement=iB,P.isEmpty=sB,P.isEqual=oB,P.isEqualWith=aB,P.isError=Op,P.isFinite=cB,P.isFunction=rs,P.isInteger=Bb,P.isLength=Mh,P.isMap=Ub,P.isMatch=lB,P.isMatchWith=uB,P.isNaN=hB,P.isNative=fB,P.isNil=pB,P.isNull=dB,P.isNumber=Fb,P.isObject=sr,P.isObjectLike=cr,P.isPlainObject=nl,P.isRegExp=Mp,P.isSafeInteger=gB,P.isSet=jb,P.isString=Ph,P.isSymbol=An,P.isTypedArray=Ua,P.isUndefined=mB,P.isWeakMap=vB,P.isWeakSet=wB,P.join=_R,P.kebabCase=aU,P.last=Kn,P.lastIndexOf=ER,P.lowerCase=cU,P.lowerFirst=lU,P.lt=yB,P.lte=bB,P.max=nF,P.maxBy=iF,P.mean=sF,P.meanBy=oF,P.min=aF,P.minBy=cF,P.stubArray=Up,P.stubFalse=Fp,P.stubObject=VU,P.stubString=GU,P.stubTrue=YU,P.multiply=lF,P.nth=AR,P.noConflict=FU,P.noop=Bp,P.now=Dh,P.pad=uU,P.padEnd=hU,P.padStart=fU,P.parseInt=dU,P.random=rU,P.reduce=IL,P.reduceRight=DL,P.repeat=pU,P.replace=gU,P.result=WB,P.round=uF,P.runInContext=Z,P.sample=OL,P.size=$L,P.snakeCase=mU,P.some=TL,P.sortedIndex=MR,P.sortedIndexBy=PR,P.sortedIndexOf=$R,P.sortedLastIndex=TR,P.sortedLastIndexBy=NR,P.sortedLastIndexOf=RR,P.startCase=wU,P.startsWith=yU,P.subtract=hF,P.sum=fF,P.sumBy=dF,P.template=bU,P.times=QU,P.toFinite=ns,P.toInteger=ft,P.toLength=qb,P.toLower=_U,P.toNumber=Wn,P.toSafeInteger=_B,P.toString=Bt,P.toUpper=EU,P.trim=AU,P.trimEnd=xU,P.trimStart=SU,P.truncate=IU,P.unescape=DU,P.uniqueId=ZU,P.upperCase=CU,P.upperFirst=Tp,P.each=Cb,P.eachRight=Ob,P.first=xb,Lp(P,function(){var s={};return Ti(P,function(a,u){qt.call(P.prototype,u)||(s[u]=a)}),s}(),{chain:!1}),P.VERSION=n,jn(["bind","bindKey","curry","curryRight","partial","partialRight"],function(s){P[s].placeholder=P}),jn(["drop","take"],function(s,a){At.prototype[s]=function(u){u=u===r?1:br(ft(u),0);var y=this.__filtered__&&!a?new At(this):this.clone();return y.__filtered__?y.__takeCount__=Ur(u,y.__takeCount__):y.__views__.push({size:Ur(u,v),type:s+(y.__dir__<0?"Right":"")}),y},At.prototype[s+"Right"]=function(u){return this.reverse()[s](u).reverse()}}),jn(["filter","map","takeWhile"],function(s,a){var u=a+1,y=u==p||u==D;At.prototype[s]=function(S){var R=this.clone();return R.__iteratees__.push({iteratee:qe(S,3),type:u}),R.__filtered__=R.__filtered__||y,R}}),jn(["head","last"],function(s,a){var u="take"+(a?"Right":"");At.prototype[s]=function(){return this[u](1).value()[0]}}),jn(["initial","tail"],function(s,a){var u="drop"+(a?"":"Right");At.prototype[s]=function(){return this.__filtered__?new At(this):this[u](1)}}),At.prototype.compact=function(){return this.filter(dn)},At.prototype.find=function(s){return this.filter(s).head()},At.prototype.findLast=function(s){return this.reverse().find(s)},At.prototype.invokeMap=gt(function(s,a){return typeof s=="function"?new At(this):this.map(function(u){return Jc(u,s,a)})}),At.prototype.reject=function(s){return this.filter(Oh(qe(s)))},At.prototype.slice=function(s,a){s=ft(s);var u=this;return u.__filtered__&&(s>0||a<0)?new At(u):(s<0?u=u.takeRight(-s):s&&(u=u.drop(s)),a!==r&&(a=ft(a),u=a<0?u.dropRight(-a):u.take(a-s)),u)},At.prototype.takeRightWhile=function(s){return this.reverse().takeWhile(s).reverse()},At.prototype.toArray=function(){return this.take(v)},Ti(At.prototype,function(s,a){var u=/^(?:filter|find|map|reject)|While$/.test(a),y=/^(?:head|last)$/.test(a),S=P[y?"take"+(a=="last"?"Right":""):a],R=y||/^find/.test(a);S&&(P.prototype[a]=function(){var G=this.__wrapped__,Q=y?[1]:arguments,X=G instanceof At,ce=Q[0],ue=X||at(G),ge=function(yt){var Dt=S.apply(P,Ms([yt],Q));return y&&we?Dt[0]:Dt};ue&&u&&typeof ce=="function"&&ce.length!=1&&(X=ue=!1);var we=this.__chain__,Le=!!this.__actions__.length,Ke=R&&!we,pt=X&&!Le;if(!R&&ue){G=pt?G:new At(this);var We=s.apply(G,Q);return We.__actions__.push({func:Sh,args:[ge],thisArg:r}),new qn(We,we)}return Ke&&pt?s.apply(this,Q):(We=this.thru(ge),Ke?y?We.value()[0]:We.value():We)})}),jn(["pop","push","shift","sort","splice","unshift"],function(s){var a=Ju[s],u=/^(?:push|sort|unshift)$/.test(s)?"tap":"thru",y=/^(?:pop|shift)$/.test(s);P.prototype[s]=function(){var S=arguments;if(y&&!this.__chain__){var R=this.value();return a.apply(at(R)?R:[],S)}return this[u](function(G){return a.apply(at(G)?G:[],S)})}}),Ti(At.prototype,function(s,a){var u=P[a];if(u){var y=u.name+"";qt.call(Ta,y)||(Ta[y]=[]),Ta[y].push({name:a,func:u})}}),Ta[wh(r,Y).name]=[{name:"wrapper",func:r}],At.prototype.clone=DT,At.prototype.reverse=CT,At.prototype.value=OT,P.prototype.at=iL,P.prototype.chain=sL,P.prototype.commit=oL,P.prototype.next=aL,P.prototype.plant=lL,P.prototype.reverse=uL,P.prototype.toJSON=P.prototype.valueOf=P.prototype.value=hL,P.prototype.first=P.prototype.head,Hc&&(P.prototype[Hc]=cL),P},Ma=oT();fr?((fr.exports=Ma)._=Ma,Gt._=Ma):It._=Ma}).call(yc)})(g0,g0.exports);var AD=Object.defineProperty,xD=Object.defineProperties,SD=Object.getOwnPropertyDescriptors,gw=Object.getOwnPropertySymbols,ID=Object.prototype.hasOwnProperty,DD=Object.prototype.propertyIsEnumerable,mw=(t,e,r)=>e in t?AD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Zl=(t,e)=>{for(var r in e||(e={}))ID.call(e,r)&&mw(t,r,e[r]);if(gw)for(var r of gw(e))DD.call(e,r)&&mw(t,r,e[r]);return t},CD=(t,e)=>xD(t,SD(e));function ds(t,e,r){var n;const i=ml(t);return((n=e.rpcMap)==null?void 0:n[i.reference])||`${ED}?chainId=${i.namespace}:${i.reference}&projectId=${r}`}function Zs(t){return t.includes(":")?t.split(":")[1]:t}function vw(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function OD(t,e){const r=Object.keys(e.namespaces).filter(i=>i.includes(t));if(!r.length)return[];const n=[];return r.forEach(i=>{const o=e.namespaces[i].accounts;n.push(...o)}),n}function m0(t={},e={}){const r=ww(t),n=ww(e);return g0.exports.merge(r,n)}function ww(t){var e,r,n,i;const o={};if(!oc(t))return o;for(const[c,l]of Object.entries(t)){const f=Tf(c)?[c]:l.chains,h=l.methods||[],g=l.events||[],_=l.rpcMap||{},E=sc(c);o[E]=CD(Zl(Zl({},o[E]),l),{chains:vl(f,(e=o[E])==null?void 0:e.chains),methods:vl(h,(r=o[E])==null?void 0:r.methods),events:vl(g,(n=o[E])==null?void 0:n.events),rpcMap:Zl(Zl({},_),(i=o[E])==null?void 0:i.rpcMap)})}return o}function MD(t){return t.includes(":")?t.split(":")[2]:t}function yw(t){const e={};for(const[r,n]of Object.entries(t)){const i=n.methods||[],o=n.events||[],c=n.accounts||[],l=Tf(r)?[r]:n.chains?n.chains:vw(n.accounts);e[r]={chains:l,methods:i,events:o,accounts:c}}return e}function v0(t){return typeof t=="number"?t:t.includes("0x")?parseInt(t,16):(t=t.includes(":")?t.split(":")[1]:t,isNaN(Number(t))?t:Number(t))}const bw={},er=t=>bw[t],w0=(t,e)=>{bw[t]=e};class PD{constructor(e){this.name="polkadot",this.namespace=e.namespace,this.events=er("events"),this.client=er("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Ki.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=Zs(r);e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||ds(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Hi(new fs(n,er("disableProviderPing")))}}var $D=Object.defineProperty,TD=Object.defineProperties,ND=Object.getOwnPropertyDescriptors,_w=Object.getOwnPropertySymbols,RD=Object.prototype.hasOwnProperty,LD=Object.prototype.propertyIsEnumerable,Ew=(t,e,r)=>e in t?$D(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Aw=(t,e)=>{for(var r in e||(e={}))RD.call(e,r)&&Ew(t,r,e[r]);if(_w)for(var r of _w(e))LD.call(e,r)&&Ew(t,r,e[r]);return t},xw=(t,e)=>TD(t,ND(e));class BD{constructor(e){this.name="eip155",this.namespace=e.namespace,this.events=er("events"),this.client=er("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(parseInt(e),r),this.chainId=parseInt(e),this.events.emit(Ki.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,r){const n=r||ds(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Hi(new fs(n,er("disableProviderPing")))}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=parseInt(Zs(r));e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}async handleSwitchChain(e){var r,n;let i=e.request.params?(r=e.request.params[0])==null?void 0:r.chainId:"0x0";i=i.startsWith("0x")?i:`0x${i}`;const o=parseInt(i,16);if(this.isChainApproved(o))this.setDefaultChain(`${o}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:i}]},chainId:(n=this.namespace.chains)==null?void 0:n[0]}),this.setDefaultChain(`${o}`);else throw new Error(`Failed to switch to chain 'eip155:${o}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var r,n,i;const o=(n=(r=e.request)==null?void 0:r.params)==null?void 0:n[0];if(!o)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const c=this.client.session.get(e.topic),l=((i=c?.sessionProperties)==null?void 0:i.capabilities)||{};if(l!=null&&l[o])return l?.[o];const f=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:xw(Aw({},c.sessionProperties||{}),{capabilities:xw(Aw({},l||{}),{[o]:f})})})}catch(h){console.warn("Failed to update session with capabilities",h)}return f}}class UD{constructor(e){this.name="solana",this.namespace=e.namespace,this.events=er("events"),this.client=er("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Ki.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=Zs(r);e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||ds(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Hi(new fs(n,er("disableProviderPing")))}}class FD{constructor(e){this.name="cosmos",this.namespace=e.namespace,this.events=er("events"),this.client=er("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Ki.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=Zs(r);e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||ds(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Hi(new fs(n,er("disableProviderPing")))}}class jD{constructor(e){this.name="cip34",this.namespace=e.namespace,this.events=er("events"),this.client=er("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Ki.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{const n=this.getCardanoRPCUrl(r),i=Zs(r);e[i]=this.createHttpProvider(i,n)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}getCardanoRPCUrl(e){const r=this.namespace.rpcMap;if(r)return r[e]}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||this.getCardanoRPCUrl(e);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Hi(new fs(n,er("disableProviderPing")))}}class kD{constructor(e){this.name="elrond",this.namespace=e.namespace,this.events=er("events"),this.client=er("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Ki.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=Zs(r);e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||ds(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Hi(new fs(n,er("disableProviderPing")))}}class qD{constructor(e){this.name="multiversx",this.namespace=e.namespace,this.events=er("events"),this.client=er("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(Ki.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=Zs(r);e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||ds(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Hi(new fs(n,er("disableProviderPing")))}}class zD{constructor(e){this.name="near",this.namespace=e.namespace,this.events=er("events"),this.client=er("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const n=r||ds(`${this.name}:${e}`,this.namespace);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(Ki.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;e[r]=this.createHttpProvider(r,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||ds(e,this.namespace);return typeof n>"u"?void 0:new Hi(new fs(n,er("disableProviderPing")))}}var HD=Object.defineProperty,KD=Object.defineProperties,WD=Object.getOwnPropertyDescriptors,Sw=Object.getOwnPropertySymbols,VD=Object.prototype.hasOwnProperty,GD=Object.prototype.propertyIsEnumerable,Iw=(t,e,r)=>e in t?HD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Xl=(t,e)=>{for(var r in e||(e={}))VD.call(e,r)&&Iw(t,r,e[r]);if(Sw)for(var r of Sw(e))GD.call(e,r)&&Iw(t,r,e[r]);return t},y0=(t,e)=>KD(t,WD(e));class b0{constructor(e){this.events=new Dr.exports,this.rpcProviders={},this.shouldAbortPairingAttempt=!1,this.maxPairingAttempts=10,this.disableProviderPing=!1,this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:yi(Hl({level:e?.logger||dw})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const r=new b0(e);return await r.initialize(),r}async request(e,r,n){const[i,o]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(i).request({request:Xl({},e),chainId:`${i}:${o}`,topic:this.session.topic,expiry:n})}sendAsync(e,r,n,i){const o=new Date().getTime();this.request(e,n,i).then(c=>r(null,Wl(o,c))).catch(c=>r(c,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:Ut("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:r,response:n}=await this.client.authenticate(e);r&&(this.uri=r,this.events.emit("display_uri",r));const i=await n();if(this.session=i.session,this.session){const o=yw(this.session.namespaces);this.namespaces=m0(this.namespaces,o),this.persist("namespaces",this.namespaces),this.onConnect()}return i}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}removeListener(e,r){this.events.removeListener(e,r)}off(e,r){this.events.off(e,r)}get isWalletConnect(){return!0}async pair(e){this.shouldAbortPairingAttempt=!1;let r=0;do{if(this.shouldAbortPairingAttempt)throw new Error("Pairing aborted");if(r>=this.maxPairingAttempts)throw new Error("Max auto pairing attempts reached");const{uri:n,approval:i}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties});n&&(this.uri=n,this.events.emit("display_uri",n)),await i().then(o=>{this.session=o;const c=yw(o.namespaces);this.namespaces=m0(this.namespaces,c),this.persist("namespaces",this.namespaces)}).catch(o=>{if(o.message!==nw)throw o;r++})}while(!this.session);return this.onConnect(),this.session}setDefaultChain(e,r){try{if(!this.session)return;const[n,i]=this.validateChain(e);this.getProvider(n).setDefaultChain(i,r)}catch(n){if(!/Please call connect/.test(n.message))throw n}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(wi(r)){for(const n of r)e.deletePairings?this.client.core.expirer.set(n.topic,0):await this.client.core.relayer.subscriber.unsubscribe(n.topic);this.logger.info(`Inactive pairings cleared: ${r.length}`)}}abortPairingAttempt(){this.shouldAbortPairingAttempt=!0}async checkStorage(){if(this.namespaces=await this.getFromStore("namespaces"),this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.client.session.length){const e=this.client.session.keys.length-1;this.session=this.client.session.get(this.client.session.keys[e]),this.createProviders()}}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){this.client=this.providerOpts.client||await d0.init({logger:this.providerOpts.logger||dw,relayUrl:this.providerOpts.relayUrl||yD,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name}),this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(r=>sc(r)))];w0("client",this.client),w0("events",this.events),w0("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const n=OD(r,this.session),i=vw(n),o=m0(this.namespaces,this.optionalNamespaces),c=y0(Xl({},o[r]),{accounts:n,chains:i});switch(r){case"eip155":this.rpcProviders[r]=new BD({namespace:c});break;case"solana":this.rpcProviders[r]=new UD({namespace:c});break;case"cosmos":this.rpcProviders[r]=new FD({namespace:c});break;case"polkadot":this.rpcProviders[r]=new PD({namespace:c});break;case"cip34":this.rpcProviders[r]=new jD({namespace:c});break;case"elrond":this.rpcProviders[r]=new kD({namespace:c});break;case"multiversx":this.rpcProviders[r]=new qD({namespace:c});break;case"near":this.rpcProviders[r]=new zD({namespace:c});break}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{const{params:r}=e,{event:n}=r;if(n.name==="accountsChanged"){const i=n.data;i&&wi(i)&&this.events.emit("accountsChanged",i.map(MD))}else if(n.name==="chainChanged"){const i=r.chainId,o=r.event.data,c=sc(i),l=v0(i)!==v0(o)?`${c}:${v0(o)}`:i;this.onChainChanged(l)}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:r})=>{var n;const{namespaces:i}=r,o=(n=this.client)==null?void 0:n.session.get(e);this.session=y0(Xl({},o),{namespaces:i}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:r})}),this.client.on("session_delete",async e=>{await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",y0(Xl({},Ut("USER_DISCONNECTED")),{data:e.topic}))}),this.on(Ki.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){if(!this.rpcProviders[e])throw new Error(`Provider not found: ${e}`);return this.rpcProviders[e]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var r;this.getProvider(e).updateNamespace((r=this.session)==null?void 0:r.namespaces[e])})}setNamespaces(e){const{namespaces:r,optionalNamespaces:n,sessionProperties:i}=e;r&&Object.keys(r).length&&(this.namespaces=r),n&&Object.keys(n).length&&(this.optionalNamespaces=n),this.sessionProperties=i,this.persist("namespaces",r),this.persist("optionalNamespaces",n)}validateChain(e){const[r,n]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[r,n];if(r&&!Object.keys(this.namespaces||{}).map(c=>sc(c)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&n)return[r,n];const i=sc(Object.keys(this.namespaces)[0]),o=this.rpcProviders[i].getDefaultChain();return[i,o]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}onChainChanged(e,r=!1){if(!this.namespaces)return;const[n,i]=this.validateChain(e);i&&(r||this.getProvider(n).setDefaultChain(i),this.namespaces[n]?this.namespaces[n].defaultChain=i:this.namespaces[`${n}:${i}`]?this.namespaces[`${n}:${i}`].defaultChain=i:this.namespaces[`${n}:${i}`]={defaultChain:i},this.persist("namespaces",this.namespaces),this.events.emit("chainChanged",i))}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.session=void 0,this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,this.persist("namespaces",void 0),this.persist("optionalNamespaces",void 0),this.persist("sessionProperties",void 0),await this.cleanupPendingPairings({deletePairings:!0})}persist(e,r){this.client.core.storage.setItem(`${pw}/${e}`,r)}async getFromStore(e){return await this.client.core.storage.getItem(`${pw}/${e}`)}}const YD=b0,QD="wc",JD="ethereum_provider",ZD=`${QD}@2:${JD}:`,XD="https://rpc.walletconnect.com/v1/",eu=["eth_sendTransaction","personal_sign"],Dw=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_sendCalls","wallet_getCapabilities","wallet_getCallsStatus","wallet_showCallsStatus"],tu=["chainChanged","accountsChanged"],Cw=["chainChanged","accountsChanged","message","disconnect","connect"];var eC=Object.defineProperty,tC=Object.defineProperties,rC=Object.getOwnPropertyDescriptors,Ow=Object.getOwnPropertySymbols,nC=Object.prototype.hasOwnProperty,iC=Object.prototype.propertyIsEnumerable,Mw=(t,e,r)=>e in t?eC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,sa=(t,e)=>{for(var r in e||(e={}))nC.call(e,r)&&Mw(t,r,e[r]);if(Ow)for(var r of Ow(e))iC.call(e,r)&&Mw(t,r,e[r]);return t},_0=(t,e)=>tC(t,rC(e));function ru(t){return Number(t[0].split(":")[1])}function nu(t){return`0x${t.toString(16)}`}function sC(t){const{chains:e,optionalChains:r,methods:n,optionalMethods:i,events:o,optionalEvents:c,rpcMap:l}=t;if(!wi(e))throw new Error("Invalid chains");const f={chains:e,methods:n||eu,events:o||tu,rpcMap:sa({},e.length?{[ru(e)]:l[ru(e)]}:{})},h=o?.filter(x=>!tu.includes(x)),g=n?.filter(x=>!eu.includes(x));if(!r&&!c&&!i&&!(h!=null&&h.length)&&!(g!=null&&g.length))return{required:e.length?f:void 0};const _=h?.length&&g?.length||!r,E={chains:[...new Set(_?f.chains.concat(r||[]):r)],methods:[...new Set(f.methods.concat(i!=null&&i.length?i:Dw))],events:[...new Set(f.events.concat(c!=null&&c.length?c:Cw))],rpcMap:l};return{required:e.length?f:void 0,optional:r.length?E:void 0}}class iu{constructor(){this.events=new Dr.exports.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=ZD,this.on=(e,r)=>(this.events.on(e,r),this),this.once=(e,r)=>(this.events.once(e,r),this),this.removeListener=(e,r)=>(this.events.removeListener(e,r),this),this.off=(e,r)=>(this.events.off(e,r),this),this.parseAccount=e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e,this.signer={},this.rpc={}}static async init(e){const r=new iu;return await r.initialize(e),r}async request(e,r){return await this.signer.request(e,this.formatChainId(this.chainId),r)}sendAsync(e,r,n){this.signer.sendAsync(e,r,this.formatChainId(this.chainId),n)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:r,optional:n}=sC(this.rpc);try{const i=await new Promise(async(c,l)=>{var f;this.rpc.showQrModal&&((f=this.modal)==null||f.subscribeModal(h=>{!h.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),l(new Error("Connection request reset. Please try again.")))})),await this.signer.connect(_0(sa({namespaces:sa({},r&&{[this.namespace]:r})},n&&{optionalNamespaces:{[this.namespace]:n}}),{pairingTopic:e?.pairingTopic})).then(h=>{c(h)}).catch(h=>{l(new Error(h.message))})});if(!i)return;const o=Y1(i.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:nu(this.chainId)})}catch(i){throw this.signer.logger.error(i),i}finally{this.modal&&this.modal.closeModal()}}async authenticate(e){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e?.chains});try{const r=await new Promise(async(i,o)=>{var c;this.rpc.showQrModal&&((c=this.modal)==null||c.subscribeModal(l=>{!l.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),o(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(_0(sa({},e),{chains:this.rpc.chains})).then(l=>{i(l)}).catch(l=>{o(new Error(l.message))})}),n=r.session;if(n){const i=Y1(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:i),this.setAccounts(i),this.events.emit("connect",{chainId:nu(this.chainId)})}return r}catch(r){throw this.signer.logger.error(r),r}finally{this.modal&&this.modal.closeModal()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:r}=e,{event:n}=r;n.name==="accountsChanged"?(this.accounts=this.parseAccounts(n.data),this.events.emit("accountsChanged",this.accounts)):n.name==="chainChanged"?this.setChainId(this.formatChainId(n.data)):this.events.emit(n.name,n.data),this.events.emit("session_event",e)}),this.signer.on("chainChanged",e=>{const r=parseInt(e);this.chainId=r,this.events.emit("chainChanged",nu(this.chainId)),this.persist()}),this.signer.on("session_update",e=>{this.events.emit("session_update",e)}),this.signer.on("session_delete",e=>{this.reset(),this.events.emit("session_delete",e),this.events.emit("disconnect",_0(sa({},Ut("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{var r,n;this.rpc.showQrModal&&((r=this.modal)==null||r.closeModal(),(n=this.modal)==null||n.openModal({uri:e})),this.events.emit("display_uri",e)})}switchEthereumChain(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const r=e.filter(n=>this.isCompatibleChainId(n)).map(n=>this.parseChainId(n));r.length&&(this.chainId=r[0],this.events.emit("chainChanged",nu(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const r=this.parseChainId(e);this.chainId=r,this.switchEthereumChain(r)}}parseAccountId(e){const[r,n,i]=e.split(":");return{chainId:`${r}:${n}`,address:i}}setAccounts(e){this.accounts=e.filter(r=>this.parseChainId(this.parseAccountId(r).chainId)===this.chainId).map(r=>this.parseAccountId(r).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var r,n;const i=(r=e?.chains)!=null?r:[],o=(n=e?.optionalChains)!=null?n:[],c=i.concat(o);if(!c.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const l=i.length?e?.methods||eu:[],f=i.length?e?.events||tu:[],h=e?.optionalMethods||[],g=e?.optionalEvents||[],_=e?.rpcMap||this.buildRpcMap(c,e.projectId),E=e?.qrModalOptions||void 0;return{chains:i?.map(x=>this.formatChainId(x)),optionalChains:o.map(x=>this.formatChainId(x)),methods:l,events:f,optionalMethods:h,optionalEvents:g,rpcMap:_,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:E,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,r){const n={};return e.forEach(i=>{n[i]=this.getRpcUrl(i,r)}),n}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?ru(this.rpc.chains):ru(this.rpc.optionalChains),this.signer=await YD.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:e.disableProviderPing,relayUrl:e.relayUrl,storageOptions:e.storageOptions}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let r;try{const{WalletConnectModal:n}=await Promise.resolve().then(function(){return CC});r=n}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(r)try{this.modal=new r(sa({projectId:this.rpc.projectId},this.rpc.qrModalOptions))}catch(n){throw this.signer.logger.error(n),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:n,rpcMap:i}=e;r&&wi(r)&&(this.rpc.chains=r.map(o=>this.formatChainId(o)),r.forEach(o=>{this.rpc.rpcMap[o]=i?.[o]||this.getRpcUrl(o)})),n&&wi(n)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=n?.map(o=>this.formatChainId(o)),n.forEach(o=>{this.rpc.rpcMap[o]=i?.[o]||this.getRpcUrl(o)}))}getRpcUrl(e,r){var n;return((n=this.rpc.rpcMap)==null?void 0:n[e])||`${XD}?chainId=eip155:${e}&projectId=${r||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),r=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:r?.accounts),this.setAccounts(r?.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(r=>this.signer.logger.warn(r))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return typeof e=="string"||e instanceof String?[this.parseAccount(e)]:e.map(r=>this.parseAccount(r))}}const oC=iu,aC=Symbol(),Pw=Object.getPrototypeOf,E0=new WeakMap,cC=t=>t&&(E0.has(t)?E0.get(t):Pw(t)===Object.prototype||Pw(t)===Array.prototype),lC=t=>cC(t)&&t[aC]||null,$w=(t,e=!0)=>{E0.set(t,e)},A0=t=>typeof t=="object"&&t!==null,ps=new WeakMap,su=new WeakSet,uC=(t=Object.is,e=(h,g)=>new Proxy(h,g),r=h=>A0(h)&&!su.has(h)&&(Array.isArray(h)||!(Symbol.iterator in h))&&!(h instanceof WeakMap)&&!(h instanceof WeakSet)&&!(h instanceof Error)&&!(h instanceof Number)&&!(h instanceof Date)&&!(h instanceof String)&&!(h instanceof RegExp)&&!(h instanceof ArrayBuffer),n=h=>{switch(h.status){case"fulfilled":return h.value;case"rejected":throw h.reason;default:throw h}},i=new WeakMap,o=(h,g,_=n)=>{const E=i.get(h);if(E?.[0]===g)return E[1];const x=Array.isArray(h)?[]:Object.create(Object.getPrototypeOf(h));return $w(x,!0),i.set(h,[g,x]),Reflect.ownKeys(h).forEach(I=>{if(Object.getOwnPropertyDescriptor(x,I))return;const k=Reflect.get(h,I),W={value:k,enumerable:!0,configurable:!0};if(su.has(k))$w(k,!1);else if(k instanceof Promise)delete W.value,W.get=()=>_(k);else if(ps.has(k)){const[Y,B]=ps.get(k);W.value=o(Y,B(),_)}Object.defineProperty(x,I,W)}),Object.preventExtensions(x)},c=new WeakMap,l=[1,1],f=h=>{if(!A0(h))throw new Error("object required");const g=c.get(h);if(g)return g;let _=l[0];const E=new Set,x=(te,ee=++l[0])=>{_!==ee&&(_=ee,E.forEach(ne=>ne(te,ee)))};let I=l[1];const k=(te=++l[1])=>(I!==te&&!E.size&&(I=te,Y.forEach(([ee])=>{const ne=ee[1](te);ne>_&&(_=ne)})),_),W=te=>(ee,ne)=>{const de=[...ee];de[1]=[te,...de[1]],x(de,ne)},Y=new Map,B=(te,ee)=>{if(Y.has(te))throw new Error("prop listener already exists");if(E.size){const ne=ee[3](W(te));Y.set(te,[ee,ne])}else Y.set(te,[ee])},z=te=>{var ee;const ne=Y.get(te);ne&&(Y.delete(te),(ee=ne[1])==null||ee.call(ne))},M=te=>(E.add(te),E.size===1&&Y.forEach(([ne,de],d)=>{if(de)throw new Error("remove already exists");const p=ne[3](W(d));Y.set(d,[ne,p])}),()=>{E.delete(te),E.size===0&&Y.forEach(([ne,de],d)=>{de&&(de(),Y.set(d,[ne]))})}),U=Array.isArray(h)?[]:Object.create(Object.getPrototypeOf(h)),m=e(U,{deleteProperty(te,ee){const ne=Reflect.get(te,ee);z(ee);const de=Reflect.deleteProperty(te,ee);return de&&x(["delete",[ee],ne]),de},set(te,ee,ne,de){const d=Reflect.has(te,ee),p=Reflect.get(te,ee,de);if(d&&(t(p,ne)||c.has(ne)&&t(p,c.get(ne))))return!0;z(ee),A0(ne)&&(ne=lC(ne)||ne);let b=ne;if(ne instanceof Promise)ne.then(D=>{ne.status="fulfilled",ne.value=D,x(["resolve",[ee],D])}).catch(D=>{ne.status="rejected",ne.reason=D,x(["reject",[ee],D])});else{!ps.has(ne)&&r(ne)&&(b=f(ne));const D=!su.has(b)&&ps.get(b);D&&B(ee,D)}return Reflect.set(te,ee,b,de),x(["set",[ee],ne,p]),!0}});c.set(h,m);const $=[U,k,o,M];return ps.set(m,$),Reflect.ownKeys(h).forEach(te=>{const ee=Object.getOwnPropertyDescriptor(h,te);"value"in ee&&(m[te]=h[te],delete ee.value,delete ee.writable),Object.defineProperty(U,te,ee)}),m})=>[f,ps,su,t,e,r,n,i,o,c,l],[hC]=uC();function gs(t={}){return hC(t)}function Xs(t,e,r){const n=ps.get(t);n||console.warn("Please use proxy object");let i;const o=[],c=n[3];let l=!1;const h=c(g=>{if(o.push(g),r){e(o.splice(0));return}i||(i=Promise.resolve().then(()=>{i=void 0,l&&e(o.splice(0))}))});return l=!0,()=>{l=!1,h()}}function fC(t,e){const r=ps.get(t);r||console.warn("Please use proxy object");const[n,i,o]=r;return o(n,i(),e)}const Ar=gs({history:["ConnectWallet"],view:"ConnectWallet",data:void 0}),rr={state:Ar,subscribe(t){return Xs(Ar,()=>t(Ar))},push(t,e){t!==Ar.view&&(Ar.view=t,e&&(Ar.data=e),Ar.history.push(t))},reset(t){Ar.view=t,Ar.history=[t]},replace(t){Ar.history.length>1&&(Ar.history[Ar.history.length-1]=t,Ar.view=t)},goBack(){if(Ar.history.length>1){Ar.history.pop();const[t]=Ar.history.slice(-1);Ar.view=t}},setData(t){Ar.data=t}},Ue={WALLETCONNECT_DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",WCM_VERSION:"WCM_VERSION",RECOMMENDED_WALLET_AMOUNT:9,isMobile(){return typeof window<"u"?!!(window.matchMedia("(pointer:coarse)").matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},isAndroid(){return Ue.isMobile()&&navigator.userAgent.toLowerCase().includes("android")},isIos(){const t=navigator.userAgent.toLowerCase();return Ue.isMobile()&&(t.includes("iphone")||t.includes("ipad"))},isHttpUrl(t){return t.startsWith("http://")||t.startsWith("https://")},isArray(t){return Array.isArray(t)&&t.length>0},formatNativeUrl(t,e,r){if(Ue.isHttpUrl(t))return this.formatUniversalUrl(t,e,r);let n=t;n.includes("://")||(n=t.replaceAll("/","").replaceAll(":",""),n=`${n}://`),n.endsWith("/")||(n=`${n}/`),this.setWalletConnectDeepLink(n,r);const i=encodeURIComponent(e);return`${n}wc?uri=${i}`},formatUniversalUrl(t,e,r){if(!Ue.isHttpUrl(t))return this.formatNativeUrl(t,e,r);let n=t;n.endsWith("/")||(n=`${n}/`),this.setWalletConnectDeepLink(n,r);const i=encodeURIComponent(e);return`${n}wc?uri=${i}`},async wait(t){return new Promise(e=>{setTimeout(e,t)})},openHref(t,e){window.open(t,e,"noreferrer noopener")},setWalletConnectDeepLink(t,e){try{localStorage.setItem(Ue.WALLETCONNECT_DEEPLINK_CHOICE,JSON.stringify({href:t,name:e}))}catch{console.info("Unable to set WalletConnect deep link")}},setWalletConnectAndroidDeepLink(t){try{const[e]=t.split("?");localStorage.setItem(Ue.WALLETCONNECT_DEEPLINK_CHOICE,JSON.stringify({href:e,name:"Android"}))}catch{console.info("Unable to set WalletConnect android deep link")}},removeWalletConnectDeepLink(){try{localStorage.removeItem(Ue.WALLETCONNECT_DEEPLINK_CHOICE)}catch{console.info("Unable to remove WalletConnect deep link")}},setModalVersionInStorage(){try{typeof localStorage<"u"&&localStorage.setItem(Ue.WCM_VERSION,"2.6.2")}catch{console.info("Unable to set Web3Modal version in storage")}},getWalletRouterData(){var t;const e=(t=rr.state.data)==null?void 0:t.Wallet;if(!e)throw new Error('Missing "Wallet" view data');return e}},dC=typeof location<"u"&&(location.hostname.includes("localhost")||location.protocol.includes("https")),Br=gs({enabled:dC,userSessionId:"",events:[],connectedWalletId:void 0}),Tw={state:Br,subscribe(t){return Xs(Br.events,()=>t(fC(Br.events[Br.events.length-1])))},initialize(){Br.enabled&&typeof(crypto==null?void 0:crypto.randomUUID)<"u"&&(Br.userSessionId=crypto.randomUUID())},setConnectedWalletId(t){Br.connectedWalletId=t},click(t){if(Br.enabled){const e={type:"CLICK",name:t.name,userSessionId:Br.userSessionId,timestamp:Date.now(),data:t};Br.events.push(e)}},track(t){if(Br.enabled){const e={type:"TRACK",name:t.name,userSessionId:Br.userSessionId,timestamp:Date.now(),data:t};Br.events.push(e)}},view(t){if(Br.enabled){const e={type:"VIEW",name:t.name,userSessionId:Br.userSessionId,timestamp:Date.now(),data:t};Br.events.push(e)}}},xi=gs({chains:void 0,walletConnectUri:void 0,isAuth:!1,isCustomDesktop:!1,isCustomMobile:!1,isDataLoaded:!1,isUiLoaded:!1}),hr={state:xi,subscribe(t){return Xs(xi,()=>t(xi))},setChains(t){xi.chains=t},setWalletConnectUri(t){xi.walletConnectUri=t},setIsCustomDesktop(t){xi.isCustomDesktop=t},setIsCustomMobile(t){xi.isCustomMobile=t},setIsDataLoaded(t){xi.isDataLoaded=t},setIsUiLoaded(t){xi.isUiLoaded=t},setIsAuth(t){xi.isAuth=t}},ou=gs({projectId:"",mobileWallets:void 0,desktopWallets:void 0,walletImages:void 0,chains:void 0,enableAuthMode:!1,enableExplorer:!0,explorerExcludedWalletIds:void 0,explorerRecommendedWalletIds:void 0,termsOfServiceUrl:void 0,privacyPolicyUrl:void 0}),wn={state:ou,subscribe(t){return Xs(ou,()=>t(ou))},setConfig(t){var e,r;Tw.initialize(),hr.setChains(t.chains),hr.setIsAuth(!!t.enableAuthMode),hr.setIsCustomMobile(!!((e=t.mobileWallets)!=null&&e.length)),hr.setIsCustomDesktop(!!((r=t.desktopWallets)!=null&&r.length)),Ue.setModalVersionInStorage(),Object.assign(ou,t)}};var pC=Object.defineProperty,Nw=Object.getOwnPropertySymbols,gC=Object.prototype.hasOwnProperty,mC=Object.prototype.propertyIsEnumerable,Rw=(t,e,r)=>e in t?pC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,vC=(t,e)=>{for(var r in e||(e={}))gC.call(e,r)&&Rw(t,r,e[r]);if(Nw)for(var r of Nw(e))mC.call(e,r)&&Rw(t,r,e[r]);return t};const x0="https://explorer-api.walletconnect.com",S0="wcm",I0="js-2.6.2";async function au(t,e){const r=vC({sdkType:S0,sdkVersion:I0},e),n=new URL(t,x0);return n.searchParams.append("projectId",wn.state.projectId),Object.entries(r).forEach(([i,o])=>{o&&n.searchParams.append(i,String(o))}),(await fetch(n)).json()}const eo={async getDesktopListings(t){return au("/w3m/v1/getDesktopListings",t)},async getMobileListings(t){return au("/w3m/v1/getMobileListings",t)},async getInjectedListings(t){return au("/w3m/v1/getInjectedListings",t)},async getAllListings(t){return au("/w3m/v1/getAllListings",t)},getWalletImageUrl(t){return`${x0}/w3m/v1/getWalletImage/${t}?projectId=${wn.state.projectId}&sdkType=${S0}&sdkVersion=${I0}`},getAssetImageUrl(t){return`${x0}/w3m/v1/getAssetImage/${t}?projectId=${wn.state.projectId}&sdkType=${S0}&sdkVersion=${I0}`}};var wC=Object.defineProperty,Lw=Object.getOwnPropertySymbols,yC=Object.prototype.hasOwnProperty,bC=Object.prototype.propertyIsEnumerable,Bw=(t,e,r)=>e in t?wC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,_C=(t,e)=>{for(var r in e||(e={}))yC.call(e,r)&&Bw(t,r,e[r]);if(Lw)for(var r of Lw(e))bC.call(e,r)&&Bw(t,r,e[r]);return t};const Uw=Ue.isMobile(),Si=gs({wallets:{listings:[],total:0,page:1},search:{listings:[],total:0,page:1},recomendedWallets:[]}),an={state:Si,async getRecomendedWallets(){const{explorerRecommendedWalletIds:t,explorerExcludedWalletIds:e}=wn.state;if(t==="NONE"||e==="ALL"&&!t)return Si.recomendedWallets;if(Ue.isArray(t)){const r={recommendedIds:t.join(",")},{listings:n}=await eo.getAllListings(r),i=Object.values(n);i.sort((o,c)=>{const l=t.indexOf(o.id),f=t.indexOf(c.id);return l-f}),Si.recomendedWallets=i}else{const{chains:r,isAuth:n}=hr.state,i=r?.join(","),o=Ue.isArray(e),c={page:1,sdks:n?"auth_v1":void 0,entries:Ue.RECOMMENDED_WALLET_AMOUNT,chains:i,version:2,excludedIds:o?e.join(","):void 0},{listings:l}=Uw?await eo.getMobileListings(c):await eo.getDesktopListings(c);Si.recomendedWallets=Object.values(l)}return Si.recomendedWallets},async getWallets(t){const e=_C({},t),{explorerRecommendedWalletIds:r,explorerExcludedWalletIds:n}=wn.state,{recomendedWallets:i}=Si;if(n==="ALL")return Si.wallets;i.length?e.excludedIds=i.map(_=>_.id).join(","):Ue.isArray(r)&&(e.excludedIds=r.join(",")),Ue.isArray(n)&&(e.excludedIds=[e.excludedIds,n].filter(Boolean).join(",")),hr.state.isAuth&&(e.sdks="auth_v1");const{page:o,search:c}=t,{listings:l,total:f}=Uw?await eo.getMobileListings(e):await eo.getDesktopListings(e),h=Object.values(l),g=c?"search":"wallets";return Si[g]={listings:[...Si[g].listings,...h],total:f,page:o??1},{listings:h,total:f}},getWalletImageUrl(t){return eo.getWalletImageUrl(t)},getAssetImageUrl(t){return eo.getAssetImageUrl(t)},resetSearch(){Si.search={listings:[],total:0,page:1}}},oa=gs({open:!1}),to={state:oa,subscribe(t){return Xs(oa,()=>t(oa))},async open(t){return new Promise(e=>{const{isUiLoaded:r,isDataLoaded:n}=hr.state;if(Ue.removeWalletConnectDeepLink(),hr.setWalletConnectUri(t?.uri),hr.setChains(t?.chains),rr.reset("ConnectWallet"),r&&n)oa.open=!0,e();else{const i=setInterval(()=>{const o=hr.state;o.isUiLoaded&&o.isDataLoaded&&(clearInterval(i),oa.open=!0,e())},200)}})},close(){oa.open=!1}};var EC=Object.defineProperty,Fw=Object.getOwnPropertySymbols,AC=Object.prototype.hasOwnProperty,xC=Object.prototype.propertyIsEnumerable,jw=(t,e,r)=>e in t?EC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,SC=(t,e)=>{for(var r in e||(e={}))AC.call(e,r)&&jw(t,r,e[r]);if(Fw)for(var r of Fw(e))xC.call(e,r)&&jw(t,r,e[r]);return t};function IC(){return typeof matchMedia<"u"&&matchMedia("(prefers-color-scheme: dark)").matches}const bc=gs({themeMode:IC()?"dark":"light"}),ms={state:bc,subscribe(t){return Xs(bc,()=>t(bc))},setThemeConfig(t){const{themeMode:e,themeVariables:r}=t;e&&(bc.themeMode=e),r&&(bc.themeVariables=SC({},r))}},ro=gs({open:!1,message:"",variant:"success"}),vs={state:ro,subscribe(t){return Xs(ro,()=>t(ro))},openToast(t,e){ro.open=!0,ro.message=t,ro.variant=e},closeToast(){ro.open=!1}};class DC{constructor(e){this.openModal=to.open,this.closeModal=to.close,this.subscribeModal=to.subscribe,this.setTheme=ms.setThemeConfig,ms.setThemeConfig(e),wn.setConfig(e),this.initUi()}async initUi(){if(typeof window<"u"){await Promise.resolve().then(function(){return L$});const e=document.createElement("wcm-modal");document.body.insertAdjacentElement("beforeend",e),hr.setIsUiLoaded(!0)}}}var CC=Object.freeze({__proto__:null,WalletConnectModal:DC});/**
|
|
70
70
|
* @license
|
|
71
71
|
* Copyright 2019 Google LLC
|
|
72
72
|
* SPDX-License-Identifier: BSD-3-Clause
|