Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@walletconnect/sign-client

Package Overview
Dependencies
Maintainers
5
Versions
378
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@walletconnect/sign-client - npm Package Compare versions

Comparing version 2.0.0-rc.1 to 2.0.0-rc.2

2

dist/index.cjs.js

@@ -1,2 +0,2 @@

"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var R=require("@walletconnect/core"),S=require("@walletconnect/logger"),V=require("@walletconnect/types"),n=require("@walletconnect/utils"),ee=require("pino"),y=require("@walletconnect/time"),p=require("@walletconnect/jsonrpc-utils"),te=require("@walletconnect/heartbeat");function se(a){return a&&typeof a=="object"&&"default"in a?a:{default:a}}var ie=se(ee);function g(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}var L=g;g.EventEmitter=g,g.prototype._events=void 0,g.prototype._maxListeners=void 0,g.defaultMaxListeners=10,g.prototype.setMaxListeners=function(a){if(!re(a)||a<0||isNaN(a))throw TypeError("n must be a positive number");return this._maxListeners=a,this},g.prototype.emit=function(a){var i,e,t,s,r,o;if(this._events||(this._events={}),a==="error"&&(!this._events.error||x(this._events.error)&&!this._events.error.length)){if(i=arguments[1],i instanceof Error)throw i;var c=new Error('Uncaught, unspecified "error" event. ('+i+")");throw c.context=i,c}if(e=this._events[a],U(e))return!1;if(I(e))switch(arguments.length){case 1:e.call(this);break;case 2:e.call(this,arguments[1]);break;case 3:e.call(this,arguments[1],arguments[2]);break;default:s=Array.prototype.slice.call(arguments,1),e.apply(this,s)}else if(x(e))for(s=Array.prototype.slice.call(arguments,1),o=e.slice(),t=o.length,r=0;r<t;r++)o[r].apply(this,s);return!0},g.prototype.addListener=function(a,i){var e;if(!I(i))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",a,I(i.listener)?i.listener:i),this._events[a]?x(this._events[a])?this._events[a].push(i):this._events[a]=[this._events[a],i]:this._events[a]=i,x(this._events[a])&&!this._events[a].warned&&(U(this._maxListeners)?e=g.defaultMaxListeners:e=this._maxListeners,e&&e>0&&this._events[a].length>e&&(this._events[a].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[a].length),typeof console.trace=="function"&&console.trace())),this},g.prototype.on=g.prototype.addListener,g.prototype.once=function(a,i){if(!I(i))throw TypeError("listener must be a function");var e=!1;function t(){this.removeListener(a,t),e||(e=!0,i.apply(this,arguments))}return t.listener=i,this.on(a,t),this},g.prototype.removeListener=function(a,i){var e,t,s,r;if(!I(i))throw TypeError("listener must be a function");if(!this._events||!this._events[a])return this;if(e=this._events[a],s=e.length,t=-1,e===i||I(e.listener)&&e.listener===i)delete this._events[a],this._events.removeListener&&this.emit("removeListener",a,i);else if(x(e)){for(r=s;r-- >0;)if(e[r]===i||e[r].listener&&e[r].listener===i){t=r;break}if(t<0)return this;e.length===1?(e.length=0,delete this._events[a]):e.splice(t,1),this._events.removeListener&&this.emit("removeListener",a,i)}return this},g.prototype.removeAllListeners=function(a){var i,e;if(!this._events)return this;if(!this._events.removeListener)return arguments.length===0?this._events={}:this._events[a]&&delete this._events[a],this;if(arguments.length===0){for(i in this._events)i!=="removeListener"&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events={},this}if(e=this._events[a],I(e))this.removeListener(a,e);else if(e)for(;e.length;)this.removeListener(a,e[e.length-1]);return delete this._events[a],this},g.prototype.listeners=function(a){var i;return!this._events||!this._events[a]?i=[]:I(this._events[a])?i=[this._events[a]]:i=this._events[a].slice(),i},g.prototype.listenerCount=function(a){if(this._events){var i=this._events[a];if(I(i))return 1;if(i)return i.length}return 0},g.listenerCount=function(a,i){return a.listenerCount(i)};function I(a){return typeof a=="function"}function re(a){return typeof a=="number"}function x(a){return typeof a=="object"&&a!==null}function U(a){return a===void 0}const G="wc",$=2,M="client",f=`${G}@${$}:${M}:`,q={name:M,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},ne={session_proposal:"session_proposal",session_update:"session_update",session_extend:"session_extend",session_ping:"session_ping",pairing_ping:"pairing_ping",session_delete:"session_delete",session_expire:"session_expire",pairing_delete:"pairing_delete",pairing_expire:"pairing_expire",session_request:"session_request",session_event:"session_event",proposal_expire:"proposal_expire"},oe={database:":memory:"},k="expirer",u={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},K="0.3",ae=y.ONE_DAY,w={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},J="history",X="0.3",j="pairing",ce=y.THIRTY_DAYS,Y="proposal",z=n.calcExpiry(y.THIRTY_DAYS),F="session",H=y.SEVEN_DAYS,P=n.calcExpiry(H),W="engine",D={wc_pairingDelete:{req:{prompt:!1,tag:1e3},res:{prompt:!1,tag:1001}},wc_pairingPing:{req:{prompt:!1,tag:1002},res:{prompt:!1,tag:1003}},wc_sessionPropose:{req:{prompt:!0,tag:1100},res:{prompt:!1,tag:1101}},wc_sessionSettle:{req:{prompt:!1,tag:1102},res:{prompt:!1,tag:1103}},wc_sessionUpdate:{req:{prompt:!1,tag:1104},res:{prompt:!1,tag:1105}},wc_sessionExtend:{req:{prompt:!1,tag:1106},res:{prompt:!1,tag:1107}},wc_sessionRequest:{req:{prompt:!0,tag:1108},res:{prompt:!1,tag:1109}},wc_sessionEvent:{req:{prompt:!0,tag:1110},res:{prompt:!1,tag:1111}},wc_sessionDelete:{req:{prompt:!1,tag:1112},res:{prompt:!1,tag:1113}},wc_sessionPing:{req:{prompt:!1,tag:1114},res:{prompt:!1,tag:1115}}};var he=Object.defineProperty,le=Object.defineProperties,pe=Object.getOwnPropertyDescriptors,Z=Object.getOwnPropertySymbols,ge=Object.prototype.hasOwnProperty,de=Object.prototype.propertyIsEnumerable,B=(a,i,e)=>i in a?he(a,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[i]=e,v=(a,i)=>{for(var e in i||(i={}))ge.call(i,e)&&B(a,e,i[e]);if(Z)for(var e of Z(i))de.call(i,e)&&B(a,e,i[e]);return a},Q=(a,i)=>le(a,pe(i));class ue extends V.IEngine{constructor(i){super(i),this.events=new L,this.initialized=!1,this.name=W,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0)},this.connect=async e=>{this.isInitialized(),await this.isValidConnect(e);const{pairingTopic:t,requiredNamespaces:s,relays:r}=e;let o=t,c,h=!1;if(o&&(h=this.client.pairing.get(o).active),!o||!h){const{topic:_,uri:d}=await this.createPairing();o=_,c=d}const l=await this.client.core.crypto.generateKeyPair(),E={requiredNamespaces:s,relays:r??[{protocol:R.RELAYER_DEFAULT_PROTOCOL}],proposer:{publicKey:l,metadata:this.client.metadata}},{reject:m,resolve:N,done:C}=n.createDelayedPromise();if(this.events.once(n.engineEvent("session_connect"),async({error:_,session:d})=>{if(_)m(_);else if(d){d.self.publicKey=l;const T=Q(v({},d),{requiredNamespaces:s});await this.client.session.set(d.topic,T),await this.setExpiry(d.topic,d.expiry),o&&await this.client.pairing.update(o,{peerMetadata:d.peer.metadata}),N(T)}}),!o){const{message:_}=n.getInternalError("NO_MATCHING_KEY",`connect() pairing topic: ${o}`);throw new Error(_)}const O=await this.sendRequest(o,"wc_sessionPropose",E),b=n.calcExpiry(y.FIVE_MINUTES);return await this.setProposal(O,v({id:O,expiry:b},E)),{uri:c,approval:C}},this.pair=async e=>{this.isInitialized(),this.isValidPair(e);const{topic:t,symKey:s,relay:r}=n.parseUri(e.uri),o=n.calcExpiry(y.FIVE_MINUTES),c={topic:t,relay:r,expiry:o,active:!1};return await this.client.pairing.set(t,c),await this.client.core.crypto.setSymKey(s,t),await this.client.core.relayer.subscribe(t,{relay:r}),await this.setExpiry(t,o),c},this.approve=async e=>{this.isInitialized(),await this.isValidApprove(e);const{id:t,relayProtocol:s,namespaces:r}=e,{pairingTopic:o,proposer:c,requiredNamespaces:h}=this.client.proposal.get(t),l=await this.client.core.crypto.generateKeyPair(),E=c.publicKey,m=await this.client.core.crypto.generateSharedKey(l,E),N={relay:{protocol:s??"iridium"},namespaces:r,requiredNamespaces:h,controller:{publicKey:l,metadata:this.client.metadata},expiry:P};await this.client.core.relayer.subscribe(m);const C=await this.sendRequest(m,"wc_sessionSettle",N),{done:O,resolve:b,reject:_}=n.createDelayedPromise();this.events.once(n.engineEvent("session_approve",C),({error:T})=>{T?_(T):b(this.client.session.get(m))});const d=Q(v({},N),{topic:m,acknowledged:!1,self:N.controller,peer:{publicKey:c.publicKey,metadata:c.metadata},controller:l});return await this.client.session.set(m,d),await this.setExpiry(m,P),o&&await this.client.pairing.update(o,{peerMetadata:d.peer.metadata}),o&&t&&(await this.sendResult(t,o,{relay:{protocol:s??"iridium"},responderPublicKey:l}),await this.client.proposal.delete(t,n.getSdkError("USER_DISCONNECTED")),await this.activatePairing(o)),{topic:m,acknowledged:O}},this.reject=async e=>{this.isInitialized(),await this.isValidReject(e);const{id:t,reason:s}=e,{pairingTopic:r}=this.client.proposal.get(t);r&&(await this.sendError(t,r,s),await this.client.proposal.delete(t,n.getSdkError("USER_DISCONNECTED")))},this.update=async e=>{this.isInitialized(),await this.isValidUpdate(e);const{topic:t,namespaces:s}=e,r=await this.sendRequest(t,"wc_sessionUpdate",{namespaces:s}),{done:o,resolve:c,reject:h}=n.createDelayedPromise();return this.events.once(n.engineEvent("session_update",r),({error:l})=>{l?h(l):c()}),await this.client.session.update(t,{namespaces:s}),{acknowledged:o}},this.extend=async e=>{this.isInitialized(),await this.isValidExtend(e);const{topic:t}=e,s=await this.sendRequest(t,"wc_sessionExtend",{}),{done:r,resolve:o,reject:c}=n.createDelayedPromise();return this.events.once(n.engineEvent("session_extend",s),({error:h})=>{h?c(h):o()}),await this.setExpiry(t,P),{acknowledged:r}},this.request=async e=>{this.isInitialized(),await this.isValidRequest(e);const{chainId:t,request:s,topic:r}=e,o=await this.sendRequest(r,"wc_sessionRequest",{request:s,chainId:t}),{done:c,resolve:h,reject:l}=n.createDelayedPromise();return this.events.once(n.engineEvent("session_request",o),({error:E,result:m})=>{E?l(E):h(m)}),await c()},this.respond=async e=>{this.isInitialized(),await this.isValidRespond(e);const{topic:t,response:s}=e,{id:r}=s;p.isJsonRpcResult(s)?await this.sendResult(r,t,s.result):p.isJsonRpcError(s)&&await this.sendError(r,t,s.error)},this.ping=async e=>{this.isInitialized(),await this.isValidPing(e);const{topic:t}=e;if(this.client.session.keys.includes(t)){const s=await this.sendRequest(t,"wc_sessionPing",{}),{done:r,resolve:o,reject:c}=n.createDelayedPromise();this.events.once(n.engineEvent("session_ping",s),({error:h})=>{h?c(h):o()}),await r()}else if(this.client.pairing.keys.includes(t)){const s=await this.sendRequest(t,"wc_pairingPing",{}),{done:r,resolve:o,reject:c}=n.createDelayedPromise();this.events.once(n.engineEvent("pairing_ping",s),({error:h})=>{h?c(h):o()}),await r()}},this.emit=async e=>{this.isInitialized(),await this.isValidEmit(e);const{topic:t,event:s,chainId:r}=e;await this.sendRequest(t,"wc_sessionEvent",{event:s,chainId:r})},this.disconnect=async e=>{this.isInitialized(),await this.isValidDisconnect(e);const{topic:t}=e;this.client.session.keys.includes(t)?(await this.sendRequest(t,"wc_sessionDelete",n.getSdkError("USER_DISCONNECTED")),await this.deleteSession(t)):this.client.pairing.keys.includes(t)&&(await this.sendRequest(t,"wc_pairingDelete",n.getSdkError("USER_DISCONNECTED")),await this.deletePairing(t))},this.find=e=>(this.isInitialized(),this.client.session.getAll().filter(t=>n.isSessionCompatible(t,e))),this.activatePairing=async e=>{await this.client.pairing.update(e,{active:!0,expiry:z}),await this.setExpiry(e,z)},this.deleteSession=async e=>{const{self:t}=this.client.session.get(e);await Promise.all([this.client.core.relayer.unsubscribe(e),this.client.session.delete(e,n.getSdkError("USER_DISCONNECTED")),this.client.core.crypto.deleteKeyPair(t.publicKey),this.client.core.crypto.deleteSymKey(e),this.client.expirer.del(e)])},this.deletePairing=async e=>{await Promise.all([this.client.core.relayer.unsubscribe(e),this.client.pairing.delete(e,n.getSdkError("USER_DISCONNECTED")),this.client.core.crypto.deleteSymKey(e),this.client.expirer.del(e)])},this.deleteProposal=async e=>{await Promise.all([this.client.proposal.delete(e,n.getSdkError("USER_DISCONNECTED")),this.client.expirer.del(e)])},this.setExpiry=async(e,t)=>{this.client.pairing.keys.includes(e)?await this.client.pairing.update(e,{expiry:t}):this.client.session.keys.includes(e)&&await this.client.session.update(e,{expiry:t}),this.client.expirer.set(e,t)},this.setProposal=async(e,t)=>{await this.client.proposal.set(e,t),this.client.expirer.set(e,t.expiry)},this.sendRequest=async(e,t,s)=>{const r=p.formatJsonRpcRequest(t,s),o=await this.client.core.crypto.encode(e,r),c=D[t].req;return await this.client.core.relayer.publish(e,o,c),this.client.history.set(e,r),r.id},this.sendResult=async(e,t,s)=>{const r=p.formatJsonRpcResult(e,s),o=await this.client.core.crypto.encode(t,r),c=await this.client.history.get(t,e),h=D[c.request.method].res;await this.client.core.relayer.publish(t,o,h),await this.client.history.resolve(r)},this.sendError=async(e,t,s)=>{const r=p.formatJsonRpcError(e,s),o=await this.client.core.crypto.encode(t,r),c=await this.client.history.get(t,e),h=D[c.request.method].res;await this.client.core.relayer.publish(t,o,h),await this.client.history.resolve(r)},this.cleanup=async()=>{const e=[],t=[],s=[];this.client.session.getAll().forEach(r=>{n.isExpired(r.expiry)&&e.push(r.topic)}),this.client.pairing.getAll().forEach(r=>{n.isExpired(r.expiry)&&t.push(r.topic)}),this.client.proposal.getAll().forEach(r=>{n.isExpired(r.expiry)&&s.push(r.id)}),await Promise.all([...e.map(this.deleteSession),...t.map(this.deletePairing),...s.map(this.deleteProposal)])},this.onRelayEventRequest=e=>{const{topic:t,payload:s}=e,r=s.method;switch(r){case"wc_sessionPropose":return this.onSessionProposeRequest(t,s);case"wc_sessionSettle":return this.onSessionSettleRequest(t,s);case"wc_sessionUpdate":return this.onSessionUpdateRequest(t,s);case"wc_sessionExtend":return this.onSessionExtendRequest(t,s);case"wc_sessionPing":return this.onSessionPingRequest(t,s);case"wc_pairingPing":return this.onPairingPingRequest(t,s);case"wc_sessionDelete":return this.onSessionDeleteRequest(t,s);case"wc_pairingDelete":return this.onPairingDeleteRequest(t,s);case"wc_sessionRequest":return this.onSessionRequest(t,s);case"wc_sessionEvent":return this.onSessionEventRequest(t,s);default:return this.client.logger.info(`Unsupported request method ${r}`)}},this.onRelayEventResponse=async e=>{const{topic:t,payload:s}=e,r=(await this.client.history.get(t,s.id)).request.method;switch(r){case"wc_sessionPropose":return this.onSessionProposeResponse(t,s);case"wc_sessionSettle":return this.onSessionSettleResponse(t,s);case"wc_sessionUpdate":return this.onSessionUpdateResponse(t,s);case"wc_sessionExtend":return this.onSessionExtendResponse(t,s);case"wc_sessionPing":return this.onSessionPingResponse(t,s);case"wc_pairingPing":return this.onPairingPingResponse(t,s);case"wc_sessionRequest":return this.onSessionRequestResponse(t,s);default:return this.client.logger.info(`Unsupported response method ${r}`)}},this.onSessionProposeRequest=async(e,t)=>{const{params:s,id:r}=t;try{this.isValidConnect(v({},t.params));const o=n.calcExpiry(y.FIVE_MINUTES),c=v({id:r,pairingTopic:e,expiry:o},s);await this.setProposal(r,c),this.client.events.emit("session_proposal",{id:r,params:c})}catch(o){await this.sendError(r,e,o),this.client.logger.error(o)}},this.onSessionProposeResponse=async(e,t)=>{const{id:s}=t;if(p.isJsonRpcResult(t)){const{result:r}=t;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:r});const o=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:o});const c=o.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const h=r.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:h});const l=await this.client.core.crypto.generateSharedKey(c,h);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:l});const E=await this.client.core.relayer.subscribe(l);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:E}),await this.activatePairing(e)}else p.isJsonRpcError(t)&&(await this.client.proposal.delete(s,n.getSdkError("USER_DISCONNECTED")),this.events.emit(n.engineEvent("session_connect"),{error:t.error}))},this.onSessionSettleRequest=async(e,t)=>{const{id:s,params:r}=t;try{this.isValidSessionSettleRequest(r);const{relay:o,controller:c,expiry:h,namespaces:l}=t.params,E={topic:e,relay:o,expiry:h,namespaces:l,acknowledged:!0,controller:c.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:c.publicKey,metadata:c.metadata}};await this.sendResult(t.id,e,!0),this.events.emit(n.engineEvent("session_connect"),{session:E})}catch(o){await this.sendError(s,e,o),this.client.logger.error(o)}},this.onSessionSettleResponse=async(e,t)=>{const{id:s}=t;p.isJsonRpcResult(t)?(await this.client.session.update(e,{acknowledged:!0}),this.events.emit(n.engineEvent("session_approve",s),{})):p.isJsonRpcError(t)&&(await this.client.session.delete(e,n.getSdkError("USER_DISCONNECTED")),this.events.emit(n.engineEvent("session_approve",s),{error:t.error}))},this.onSessionUpdateRequest=async(e,t)=>{const{params:s,id:r}=t;try{this.isValidUpdate(v({topic:e},s)),await this.client.session.update(e,{namespaces:s.namespaces}),await this.sendResult(r,e,!0),this.client.events.emit("session_update",{id:r,topic:e,params:s})}catch(o){await this.sendError(r,e,o),this.client.logger.error(o)}},this.onSessionUpdateResponse=(e,t)=>{const{id:s}=t;p.isJsonRpcResult(t)?this.events.emit(n.engineEvent("session_update",s),{}):p.isJsonRpcError(t)&&this.events.emit(n.engineEvent("session_update",s),{error:t.error})},this.onSessionExtendRequest=async(e,t)=>{const{id:s}=t;try{this.isValidExtend({topic:e}),await this.setExpiry(e,P),await this.sendResult(s,e,!0),this.client.events.emit("session_extend",{id:s,topic:e})}catch(r){await this.sendError(s,e,r),this.client.logger.error(r)}},this.onSessionExtendResponse=(e,t)=>{const{id:s}=t;p.isJsonRpcResult(t)?this.events.emit(n.engineEvent("session_extend",s),{}):p.isJsonRpcError(t)&&this.events.emit(n.engineEvent("session_extend",s),{error:t.error})},this.onSessionPingRequest=async(e,t)=>{const{id:s}=t;try{this.isValidPing({topic:e}),await this.sendResult(s,e,!0),this.client.events.emit("session_ping",{id:s,topic:e})}catch(r){await this.sendError(s,e,r),this.client.logger.error(r)}},this.onSessionPingResponse=(e,t)=>{const{id:s}=t;p.isJsonRpcResult(t)?this.events.emit(n.engineEvent("session_ping",s),{}):p.isJsonRpcError(t)&&this.events.emit(n.engineEvent("session_ping",s),{error:t.error})},this.onPairingPingRequest=async(e,t)=>{const{id:s}=t;try{this.isValidPing({topic:e}),await this.sendResult(s,e,!0),this.client.events.emit("pairing_ping",{id:s,topic:e})}catch(r){await this.sendError(s,e,r),this.client.logger.error(r)}},this.onPairingPingResponse=(e,t)=>{const{id:s}=t;p.isJsonRpcResult(t)?this.events.emit(n.engineEvent("pairing_ping",s),{}):p.isJsonRpcError(t)&&this.events.emit(n.engineEvent("pairing_ping",s),{error:t.error})},this.onSessionDeleteRequest=async(e,t)=>{const{id:s}=t;try{this.isValidDisconnect({topic:e,reason:t.params}),await this.sendResult(s,e,!0),await this.deleteSession(e),this.client.events.emit("session_delete",{id:s,topic:e})}catch(r){await this.sendError(s,e,r),this.client.logger.error(r)}},this.onPairingDeleteRequest=async(e,t)=>{const{id:s}=t;try{this.isValidDisconnect({topic:e,reason:t.params}),await this.sendResult(s,e,!0),await this.deletePairing(e),this.client.events.emit("pairing_delete",{id:s,topic:e})}catch(r){await this.sendError(s,e,r),this.client.logger.error(r)}},this.onSessionRequest=async(e,t)=>{const{id:s,params:r}=t;try{this.isValidRequest(v({topic:e},r)),this.client.events.emit("session_request",{id:s,topic:e,params:r})}catch(o){await this.sendError(s,e,o),this.client.logger.error(o)}},this.onSessionRequestResponse=(e,t)=>{const{id:s}=t;p.isJsonRpcResult(t)?this.events.emit(n.engineEvent("session_request",s),{result:t.result}):p.isJsonRpcError(t)&&this.events.emit(n.engineEvent("session_request",s),{error:t.error})},this.onSessionEventRequest=async(e,t)=>{const{id:s,params:r}=t;try{this.isValidEmit(v({topic:e},r)),this.client.events.emit("session_event",{id:s,topic:e,params:r})}catch(o){await this.sendError(s,e,o),this.client.logger.error(o)}},this.isValidConnect=async e=>{if(!n.isValidParams(e)){const{message:c}=n.getInternalError("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(e)}`);throw new Error(c)}const{pairingTopic:t,requiredNamespaces:s,relays:r}=e;n.isUndefined(t)||await this.isValidPairingTopic(t);const o=n.isValidRequiredNamespaces(s,"connect()");if(o)throw new Error(o.message);if(!n.isValidRelays(r,!0)){const{message:c}=n.getInternalError("MISSING_OR_INVALID",`connect() relays: ${r}`);throw new Error(c)}},this.isValidPair=e=>{if(!n.isValidParams(e)){const{message:t}=n.getInternalError("MISSING_OR_INVALID",`pair() params: ${e}`);throw new Error(t)}if(!n.isValidUrl(e.uri)){const{message:t}=n.getInternalError("MISSING_OR_INVALID",`pair() uri: ${e.uri}`);throw new Error(t)}},this.isValidApprove=async e=>{if(!n.isValidParams(e))throw new Error(n.getInternalError("MISSING_OR_INVALID",`approve() params: ${e}`).message);const{id:t,namespaces:s,relayProtocol:r}=e;await this.isValidProposalId(t);const o=this.client.proposal.get(t),c=n.isValidNamespaces(s,"approve()");if(c)throw new Error(c.message);const h=n.isConformingNamespaces(o.requiredNamespaces,s,"update()");if(h)throw new Error(h.message);if(!n.isValidString(r,!0)){const{message:l}=n.getInternalError("MISSING_OR_INVALID",`approve() relayProtocol: ${r}`);throw new Error(l)}},this.isValidReject=async e=>{if(!n.isValidParams(e)){const{message:r}=n.getInternalError("MISSING_OR_INVALID",`reject() params: ${e}`);throw new Error(r)}const{id:t,reason:s}=e;if(await this.isValidProposalId(t),!n.isValidErrorReason(s)){const{message:r}=n.getInternalError("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(s)}`);throw new Error(r)}},this.isValidSessionSettleRequest=e=>{if(!n.isValidParams(e)){const{message:l}=n.getInternalError("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${e}`);throw new Error(l)}const{relay:t,controller:s,namespaces:r,expiry:o}=e;if(!n.isValidRelay(t)){const{message:l}=n.getInternalError("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const c=n.isValidController(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);const h=n.isValidNamespaces(r,"onSessionSettleRequest()");if(h)throw new Error(h.message);if(n.isExpired(o)){const{message:l}=n.getInternalError("EXPIRED","onSessionSettleRequest()");throw new Error(l)}},this.isValidUpdate=async e=>{if(!n.isValidParams(e)){const{message:h}=n.getInternalError("MISSING_OR_INVALID",`update() params: ${e}`);throw new Error(h)}const{topic:t,namespaces:s}=e;await this.isValidSessionTopic(t);const r=this.client.session.get(t),o=n.isValidNamespaces(s,"update()");if(o)throw new Error(o.message);const c=n.isConformingNamespaces(r.requiredNamespaces,s,"update()");if(c)throw new Error(c.message)},this.isValidExtend=async e=>{if(!n.isValidParams(e)){const{message:s}=n.getInternalError("MISSING_OR_INVALID",`extend() params: ${e}`);throw new Error(s)}const{topic:t}=e;await this.isValidSessionTopic(t)},this.isValidRequest=async e=>{if(!n.isValidParams(e)){const{message:c}=n.getInternalError("MISSING_OR_INVALID",`request() params: ${e}`);throw new Error(c)}const{topic:t,request:s,chainId:r}=e;await this.isValidSessionTopic(t);const{namespaces:o}=this.client.session.get(t);if(!n.isValidNamespacesChainId(o,r)){const{message:c}=n.getInternalError("MISSING_OR_INVALID",`request() chainId: ${r}`);throw new Error(c)}if(!n.isValidRequest(s)){const{message:c}=n.getInternalError("MISSING_OR_INVALID",`request() ${JSON.stringify(s)}`);throw new Error(c)}if(!n.isValidNamespacesRequest(o,r,s.method)){const{message:c}=n.getInternalError("MISSING_OR_INVALID",`request() method: ${s.method}`);throw new Error(c)}},this.isValidRespond=async e=>{if(!n.isValidParams(e)){const{message:r}=n.getInternalError("MISSING_OR_INVALID",`respond() params: ${e}`);throw new Error(r)}const{topic:t,response:s}=e;if(await this.isValidSessionTopic(t),!n.isValidResponse(s)){const{message:r}=n.getInternalError("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(r)}},this.isValidPing=async e=>{if(!n.isValidParams(e)){const{message:s}=n.getInternalError("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(s)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)},this.isValidEmit=async e=>{if(!n.isValidParams(e)){const{message:c}=n.getInternalError("MISSING_OR_INVALID",`emit() params: ${e}`);throw new Error(c)}const{topic:t,event:s,chainId:r}=e;await this.isValidSessionTopic(t);const{namespaces:o}=this.client.session.get(t);if(!n.isValidNamespacesChainId(o,r)){const{message:c}=n.getInternalError("MISSING_OR_INVALID",`emit() chainId: ${r}`);throw new Error(c)}if(!n.isValidEvent(s)){const{message:c}=n.getInternalError("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(c)}if(!n.isValidNamespacesEvent(o,r,s.name)){const{message:c}=n.getInternalError("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(c)}},this.isValidDisconnect=async e=>{if(!n.isValidParams(e)){const{message:s}=n.getInternalError("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(s)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)}}async createPairing(){const i=n.generateRandomBytes32(),e=await this.client.core.crypto.setSymKey(i),t=n.calcExpiry(y.FIVE_MINUTES),s={protocol:R.RELAYER_DEFAULT_PROTOCOL},r={topic:e,expiry:t,relay:s,active:!1},o=n.formatUri({protocol:this.client.protocol,version:this.client.version,topic:e,symKey:i,relay:s});return await this.client.pairing.set(e,r),await this.client.core.relayer.subscribe(e),await this.setExpiry(e,t),{topic:e,uri:o}}isInitialized(){if(!this.initialized){const{message:i}=n.getInternalError("NOT_INITIALIZED",this.name);throw new Error(i)}}registerRelayerEvents(){this.client.core.relayer.on(R.RELAYER_EVENTS.message,async i=>{const{topic:e,message:t}=i,s=await this.client.core.crypto.decode(e,t);p.isJsonRpcRequest(s)?(this.client.history.set(e,s),this.onRelayEventRequest({topic:e,payload:s})):p.isJsonRpcResponse(s)&&(await this.client.history.resolve(s),this.onRelayEventResponse({topic:e,payload:s}))})}registerExpirerEvents(){this.client.expirer.on(u.expired,async i=>{const{topic:e,id:t}=n.parseExpirerTarget(i.target);e?this.client.session.keys.includes(e)?(await this.deleteSession(e),this.client.events.emit("session_expire",{topic:e})):this.client.pairing.keys.includes(e)&&(await this.deletePairing(e),this.client.events.emit("pairing_expire",{topic:e})):t&&await this.deleteProposal(t)})}async isValidPairingTopic(i){if(!n.isValidString(i,!1)){const{message:e}=n.getInternalError("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(e)}if(!this.client.pairing.keys.includes(i)){const{message:e}=n.getInternalError("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(e)}if(n.isExpired(this.client.pairing.get(i).expiry)){await this.deletePairing(i);const{message:e}=n.getInternalError("EXPIRED",`pairing topic: ${i}`);throw new Error(e)}}async isValidSessionTopic(i){if(!n.isValidString(i,!1)){const{message:e}=n.getInternalError("MISSING_OR_INVALID",`session topic should be a string: ${i}`);throw new Error(e)}if(!this.client.session.keys.includes(i)){const{message:e}=n.getInternalError("NO_MATCHING_KEY",`session topic doesn't exist: ${i}`);throw new Error(e)}if(n.isExpired(this.client.session.get(i).expiry)){await this.deleteSession(i);const{message:e}=n.getInternalError("EXPIRED",`session topic: ${i}`);throw new Error(e)}}async isValidSessionOrPairingTopic(i){if(this.client.session.keys.includes(i))await this.isValidSessionTopic(i);else if(this.client.pairing.keys.includes(i))await this.isValidPairingTopic(i);else if(n.isValidString(i,!1)){const{message:e}=n.getInternalError("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${i}`);throw new Error(e)}else{const{message:e}=n.getInternalError("MISSING_OR_INVALID",`session or pairing topic should be a string: ${i}`);throw new Error(e)}}async isValidProposalId(i){if(!n.isValidId(i)){const{message:e}=n.getInternalError("MISSING_OR_INVALID",`proposal id should be a number: ${i}`);throw new Error(e)}if(!this.client.proposal.keys.includes(i)){const{message:e}=n.getInternalError("NO_MATCHING_KEY",`proposal id doesn't exist: ${i}`);throw new Error(e)}if(n.isExpired(this.client.proposal.get(i).expiry)){await this.deleteProposal(i);const{message:e}=n.getInternalError("EXPIRED",`proposal id: ${i}`);throw new Error(e)}}}class Ee extends V.IExpirer{constructor(i,e){super(i,e),this.core=i,this.logger=e,this.expirations=new Map,this.events=new L.EventEmitter,this.name=k,this.version=K,this.cached=[],this.initialized=!1,this.storagePrefix=f,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(t=>this.expirations.set(t.target,t)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=t=>{try{const s=this.formatTarget(t);return typeof this.getExpiration(s)<"u"}catch{return!1}},this.set=(t,s)=>{this.isInitialized();const r=this.formatTarget(t),o={target:r,expiry:s};this.expirations.set(r,o),this.checkExpiry(r,o),this.events.emit(u.created,{target:r,expiration:o})},this.get=t=>{this.isInitialized();const s=this.formatTarget(t);return this.getExpiration(s)},this.del=t=>{this.isInitialized();const s=this.formatTarget(t);if(this.has(s)){const r=this.getExpiration(s);this.expirations.delete(s),this.events.emit(u.deleted,{target:s,expiration:r})}},this.on=(t,s)=>{this.events.on(t,s)},this.once=(t,s)=>{this.events.once(t,s)},this.off=(t,s)=>{this.events.off(t,s)},this.removeListener=(t,s)=>{this.events.removeListener(t,s)},this.logger=S.generateChildLogger(e,this.name)}get context(){return S.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(i){if(typeof i=="string")return n.formatTopicTarget(i);if(typeof i=="number")return n.formatIdTarget(i);const{message:e}=n.getInternalError("UNKNOWN_TYPE",`Target type: ${typeof i}`);throw new Error(e)}async setExpirations(i){await this.core.storage.setItem(this.storageKey,i)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(u.sync)}async restore(){try{const i=await this.getExpirations();if(typeof i>"u"||!i.length)return;if(this.expirations.size){const{message:e}=n.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}this.cached=i,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(i){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(i)}}getExpiration(i){const e=this.expirations.get(i);if(!e){const{message:t}=n.getInternalError("NO_MATCHING_KEY",`${this.name}: ${i}`);throw this.logger.error(t),new Error(t)}return e}checkExpiry(i,e){const{expiry:t}=e;y.toMiliseconds(t)-Date.now()<=0&&this.expire(i,e)}expire(i,e){this.expirations.delete(i),this.events.emit(u.expired,{target:i,expiration:e})}checkExpirations(){this.expirations.forEach((i,e)=>this.checkExpiry(e,i))}registerEventListeners(){this.core.heartbeat.on(te.HEARTBEAT_EVENTS.pulse,()=>this.checkExpirations()),this.events.on(u.created,i=>{const e=u.created;this.logger.info(`Emitting ${e}`),this.logger.debug({type:"event",event:e,data:i}),this.persist()}),this.events.on(u.expired,i=>{const e=u.expired;this.logger.info(`Emitting ${e}`),this.logger.debug({type:"event",event:e,data:i}),this.persist()}),this.events.on(u.deleted,i=>{const e=u.deleted;this.logger.info(`Emitting ${e}`),this.logger.debug({type:"event",event:e,data:i}),this.persist()})}isInitialized(){if(!this.initialized){const{message:i}=n.getInternalError("NOT_INITIALIZED",this.name);throw new Error(i)}}}class me extends V.IJsonRpcHistory{constructor(i,e){super(i,e),this.core=i,this.logger=e,this.records=new Map,this.events=new L.EventEmitter,this.name=J,this.version=X,this.cached=[],this.initialized=!1,this.storagePrefix=f,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(t=>this.records.set(t.id,t)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(t,s,r)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:t,request:s,chainId:r}),this.records.has(s.id))return;const o={id:s.id,topic:t,request:{method:s.method,params:s.params||null},chainId:r};this.records.set(o.id,o),this.events.emit(w.created,o)},this.resolve=async t=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:t}),!this.records.has(t.id))return;const s=await this.getRecord(t.id);typeof s.response>"u"&&(s.response=p.isJsonRpcError(t)?{error:t.error}:{result:t.result},this.records.set(s.id,s),this.events.emit(w.updated,s))},this.get=async(t,s)=>{this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:t,id:s});const r=await this.getRecord(s);if(r.topic!==t){const{message:o}=n.getInternalError("MISMATCHED_TOPIC",`${this.name}, ${s}`);throw this.logger.error(o),new Error(o)}return r},this.delete=(t,s)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:s}),this.values.forEach(r=>{if(r.topic===t){if(typeof s<"u"&&r.id!==s)return;this.records.delete(r.id),this.events.emit(w.deleted,r)}})},this.exists=async(t,s)=>(this.isInitialized(),this.records.has(s)?(await this.getRecord(s)).topic===t:!1),this.on=(t,s)=>{this.events.on(t,s)},this.once=(t,s)=>{this.events.once(t,s)},this.off=(t,s)=>{this.events.off(t,s)},this.removeListener=(t,s)=>{this.events.removeListener(t,s)},this.logger=S.generateChildLogger(e,this.name)}get context(){return S.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const i=[];return this.values.forEach(e=>{if(typeof e.response<"u")return;const t={topic:e.topic,request:p.formatJsonRpcRequest(e.request.method,e.request.params,e.id),chainId:e.chainId};return i.push(t)}),i}async setJsonRpcRecords(i){await this.core.storage.setItem(this.storageKey,i)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(i){this.isInitialized();const e=this.records.get(i);if(!e){const{message:t}=n.getInternalError("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(t)}return e}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(w.sync)}async restore(){try{const i=await this.getJsonRpcRecords();if(typeof i>"u"||!i.length)return;if(this.records.size){const{message:e}=n.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}this.cached=i,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}}registerEventListeners(){this.events.on(w.created,i=>{const e=w.created;this.logger.info(`Emitting ${e}`),this.logger.debug({type:"event",event:e,record:i}),this.persist()}),this.events.on(w.updated,i=>{const e=w.updated;this.logger.info(`Emitting ${e}`),this.logger.debug({type:"event",event:e,record:i}),this.persist()}),this.events.on(w.deleted,i=>{const e=w.deleted;this.logger.info(`Emitting ${e}`),this.logger.debug({type:"event",event:e,record:i}),this.persist()})}isInitialized(){if(!this.initialized){const{message:i}=n.getInternalError("NOT_INITIALIZED",this.name);throw new Error(i)}}}class we extends R.Store{constructor(i,e){super(i,e,j,f),this.core=i,this.logger=e}}class ye extends R.Store{constructor(i,e){super(i,e,Y,f),this.core=i,this.logger=e}}class Ie extends R.Store{constructor(i,e){super(i,e,F,f),this.core=i,this.logger=e}}class A extends V.ISignClient{constructor(i){super(i),this.protocol=G,this.version=$,this.name=q.name,this.events=new L.EventEmitter,this.on=(t,s)=>this.events.on(t,s),this.once=(t,s)=>this.events.once(t,s),this.off=(t,s)=>this.events.off(t,s),this.removeListener=(t,s)=>this.events.removeListener(t,s),this.connect=async t=>{try{return await this.engine.connect(t)}catch(s){throw this.logger.error(s.message),s}},this.pair=async t=>{try{return await this.engine.pair(t)}catch(s){throw this.logger.error(s.message),s}},this.approve=async t=>{try{return await this.engine.approve(t)}catch(s){throw this.logger.error(s.message),s}},this.reject=async t=>{try{return await this.engine.reject(t)}catch(s){throw this.logger.error(s.message),s}},this.update=async t=>{try{return await this.engine.update(t)}catch(s){throw this.logger.error(s.message),s}},this.extend=async t=>{try{return await this.engine.extend(t)}catch(s){throw this.logger.error(s.message),s}},this.request=async t=>{try{return await this.engine.request(t)}catch(s){throw this.logger.error(s.message),s}},this.respond=async t=>{try{return await this.engine.respond(t)}catch(s){throw this.logger.error(s.message),s}},this.ping=async t=>{try{return await this.engine.ping(t)}catch(s){throw this.logger.error(s.message),s}},this.emit=async t=>{try{return await this.engine.emit(t)}catch(s){throw this.logger.error(s.message),s}},this.disconnect=async t=>{try{return await this.engine.disconnect(t)}catch(s){throw this.logger.error(s.message),s}},this.find=t=>{try{return this.engine.find(t)}catch(s){throw this.logger.error(s.message),s}},this.name=i?.name||q.name,this.metadata=i?.metadata||n.getAppMetadata();const e=typeof i?.logger<"u"&&typeof i?.logger!="string"?i.logger:ie.default(S.getDefaultLoggerOptions({level:i?.logger||q.logger}));this.core=i?.core||new R.Core(i),this.logger=S.generateChildLogger(e,this.name),this.pairing=new we(this.core,this.logger),this.session=new Ie(this.core,this.logger),this.proposal=new ye(this.core,this.logger),this.history=new me(this.core,this.logger),this.expirer=new Ee(this.core,this.logger),this.engine=new ue(this)}static async init(i){const e=new A(i);return await e.initialize(),e}get context(){return S.getLoggerContext(this.logger)}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.pairing.init(),await this.session.init(),await this.proposal.init(),await this.history.init(),await this.expirer.init(),await this.engine.init(),this.logger.info("SignClient Initilization Success")}catch(i){throw this.logger.info("SignClient Initilization Failure"),this.logger.error(i.message),i}}}const _e=A;exports.ENGINE_CONTEXT=W,exports.ENGINE_RPC_OPTS=D,exports.EXPIRER_CONTEXT=k,exports.EXPIRER_DEFAULT_TTL=ae,exports.EXPIRER_EVENTS=u,exports.EXPIRER_STORAGE_VERSION=K,exports.HISTORY_CONTEXT=J,exports.HISTORY_EVENTS=w,exports.HISTORY_STORAGE_VERSION=X,exports.PAIRING_CONTEXT=j,exports.PAIRING_DEFAULT_TTL=ce,exports.PROPOSAL_CONTEXT=Y,exports.PROPOSAL_EXPIRY=z,exports.SESSION_CONTEXT=F,exports.SESSION_DEFAULT_TTL=H,exports.SESSION_EXPIRY=P,exports.SIGN_CLIENT_CONTEXT=M,exports.SIGN_CLIENT_DEFAULT=q,exports.SIGN_CLIENT_EVENTS=ne,exports.SIGN_CLIENT_PROTOCOL=G,exports.SIGN_CLIENT_STORAGE_OPTIONS=oe,exports.SIGN_CLIENT_STORAGE_PREFIX=f,exports.SIGN_CLIENT_VERSION=$,exports.SignClient=_e,exports.default=A;
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var R=require("@walletconnect/core"),S=require("@walletconnect/logger"),V=require("@walletconnect/types"),n=require("@walletconnect/utils"),ee=require("pino"),y=require("@walletconnect/time"),p=require("@walletconnect/jsonrpc-utils"),te=require("@walletconnect/heartbeat");function se(a){return a&&typeof a=="object"&&"default"in a?a:{default:a}}var ie=se(ee);function g(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}var L=g;g.EventEmitter=g,g.prototype._events=void 0,g.prototype._maxListeners=void 0,g.defaultMaxListeners=10,g.prototype.setMaxListeners=function(a){if(!re(a)||a<0||isNaN(a))throw TypeError("n must be a positive number");return this._maxListeners=a,this},g.prototype.emit=function(a){var i,e,t,s,r,o;if(this._events||(this._events={}),a==="error"&&(!this._events.error||x(this._events.error)&&!this._events.error.length)){if(i=arguments[1],i instanceof Error)throw i;var c=new Error('Uncaught, unspecified "error" event. ('+i+")");throw c.context=i,c}if(e=this._events[a],U(e))return!1;if(I(e))switch(arguments.length){case 1:e.call(this);break;case 2:e.call(this,arguments[1]);break;case 3:e.call(this,arguments[1],arguments[2]);break;default:s=Array.prototype.slice.call(arguments,1),e.apply(this,s)}else if(x(e))for(s=Array.prototype.slice.call(arguments,1),o=e.slice(),t=o.length,r=0;r<t;r++)o[r].apply(this,s);return!0},g.prototype.addListener=function(a,i){var e;if(!I(i))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",a,I(i.listener)?i.listener:i),this._events[a]?x(this._events[a])?this._events[a].push(i):this._events[a]=[this._events[a],i]:this._events[a]=i,x(this._events[a])&&!this._events[a].warned&&(U(this._maxListeners)?e=g.defaultMaxListeners:e=this._maxListeners,e&&e>0&&this._events[a].length>e&&(this._events[a].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[a].length),typeof console.trace=="function"&&console.trace())),this},g.prototype.on=g.prototype.addListener,g.prototype.once=function(a,i){if(!I(i))throw TypeError("listener must be a function");var e=!1;function t(){this.removeListener(a,t),e||(e=!0,i.apply(this,arguments))}return t.listener=i,this.on(a,t),this},g.prototype.removeListener=function(a,i){var e,t,s,r;if(!I(i))throw TypeError("listener must be a function");if(!this._events||!this._events[a])return this;if(e=this._events[a],s=e.length,t=-1,e===i||I(e.listener)&&e.listener===i)delete this._events[a],this._events.removeListener&&this.emit("removeListener",a,i);else if(x(e)){for(r=s;r-- >0;)if(e[r]===i||e[r].listener&&e[r].listener===i){t=r;break}if(t<0)return this;e.length===1?(e.length=0,delete this._events[a]):e.splice(t,1),this._events.removeListener&&this.emit("removeListener",a,i)}return this},g.prototype.removeAllListeners=function(a){var i,e;if(!this._events)return this;if(!this._events.removeListener)return arguments.length===0?this._events={}:this._events[a]&&delete this._events[a],this;if(arguments.length===0){for(i in this._events)i!=="removeListener"&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events={},this}if(e=this._events[a],I(e))this.removeListener(a,e);else if(e)for(;e.length;)this.removeListener(a,e[e.length-1]);return delete this._events[a],this},g.prototype.listeners=function(a){var i;return!this._events||!this._events[a]?i=[]:I(this._events[a])?i=[this._events[a]]:i=this._events[a].slice(),i},g.prototype.listenerCount=function(a){if(this._events){var i=this._events[a];if(I(i))return 1;if(i)return i.length}return 0},g.listenerCount=function(a,i){return a.listenerCount(i)};function I(a){return typeof a=="function"}function re(a){return typeof a=="number"}function x(a){return typeof a=="object"&&a!==null}function U(a){return a===void 0}const G="wc",$=2,M="client",f=`${G}@${$}:${M}:`,q={name:M,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},ne={session_proposal:"session_proposal",session_update:"session_update",session_extend:"session_extend",session_ping:"session_ping",pairing_ping:"pairing_ping",session_delete:"session_delete",session_expire:"session_expire",pairing_delete:"pairing_delete",pairing_expire:"pairing_expire",session_request:"session_request",session_event:"session_event",proposal_expire:"proposal_expire"},oe={database:":memory:"},k="expirer",u={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},K="0.3",ae=y.ONE_DAY,w={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},J="history",X="0.3",j="pairing",ce=y.THIRTY_DAYS,Y="proposal",z=n.calcExpiry(y.THIRTY_DAYS),F="session",H=y.SEVEN_DAYS,P=n.calcExpiry(H),W="engine",D={wc_pairingDelete:{req:{prompt:!1,tag:1e3},res:{prompt:!1,tag:1001}},wc_pairingPing:{req:{prompt:!1,tag:1002},res:{prompt:!1,tag:1003}},wc_sessionPropose:{req:{prompt:!0,tag:1100},res:{prompt:!1,tag:1101}},wc_sessionSettle:{req:{prompt:!1,tag:1102},res:{prompt:!1,tag:1103}},wc_sessionUpdate:{req:{prompt:!1,tag:1104},res:{prompt:!1,tag:1105}},wc_sessionExtend:{req:{prompt:!1,tag:1106},res:{prompt:!1,tag:1107}},wc_sessionRequest:{req:{prompt:!0,tag:1108},res:{prompt:!1,tag:1109}},wc_sessionEvent:{req:{prompt:!0,tag:1110},res:{prompt:!1,tag:1111}},wc_sessionDelete:{req:{prompt:!1,tag:1112},res:{prompt:!1,tag:1113}},wc_sessionPing:{req:{prompt:!1,tag:1114},res:{prompt:!1,tag:1115}}};var he=Object.defineProperty,le=Object.defineProperties,pe=Object.getOwnPropertyDescriptors,Z=Object.getOwnPropertySymbols,ge=Object.prototype.hasOwnProperty,de=Object.prototype.propertyIsEnumerable,B=(a,i,e)=>i in a?he(a,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[i]=e,v=(a,i)=>{for(var e in i||(i={}))ge.call(i,e)&&B(a,e,i[e]);if(Z)for(var e of Z(i))de.call(i,e)&&B(a,e,i[e]);return a},Q=(a,i)=>le(a,pe(i));class ue extends V.IEngine{constructor(i){super(i),this.events=new L,this.initialized=!1,this.name=W,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0)},this.connect=async e=>{this.isInitialized(),await this.isValidConnect(e);const{pairingTopic:t,requiredNamespaces:s,relays:r}=e;let o=t,c,h=!1;if(o&&(h=this.client.pairing.get(o).active),!o||!h){const{topic:_,uri:d}=await this.createPairing();o=_,c=d}const l=await this.client.core.crypto.generateKeyPair(),E={requiredNamespaces:s,relays:r??[{protocol:R.RELAYER_DEFAULT_PROTOCOL}],proposer:{publicKey:l,metadata:this.client.metadata}},{reject:m,resolve:N,done:C}=n.createDelayedPromise();if(this.events.once(n.engineEvent("session_connect"),async({error:_,session:d})=>{if(_)m(_);else if(d){d.self.publicKey=l;const T=Q(v({},d),{requiredNamespaces:s});await this.client.session.set(d.topic,T),await this.setExpiry(d.topic,d.expiry),o&&await this.client.pairing.update(o,{peerMetadata:d.peer.metadata}),N(T)}}),!o){const{message:_}=n.getInternalError("NO_MATCHING_KEY",`connect() pairing topic: ${o}`);throw new Error(_)}const O=await this.sendRequest(o,"wc_sessionPropose",E),b=n.calcExpiry(y.FIVE_MINUTES);return await this.setProposal(O,v({id:O,expiry:b},E)),{uri:c,approval:C}},this.pair=async e=>{this.isInitialized(),this.isValidPair(e);const{topic:t,symKey:s,relay:r}=n.parseUri(e.uri),o=n.calcExpiry(y.FIVE_MINUTES),c={topic:t,relay:r,expiry:o,active:!1};return await this.client.pairing.set(t,c),await this.client.core.crypto.setSymKey(s,t),await this.client.core.relayer.subscribe(t,{relay:r}),await this.setExpiry(t,o),c},this.approve=async e=>{this.isInitialized(),await this.isValidApprove(e);const{id:t,relayProtocol:s,namespaces:r}=e,{pairingTopic:o,proposer:c,requiredNamespaces:h}=this.client.proposal.get(t),l=await this.client.core.crypto.generateKeyPair(),E=c.publicKey,m=await this.client.core.crypto.generateSharedKey(l,E),N={relay:{protocol:s??"irn"},namespaces:r,requiredNamespaces:h,controller:{publicKey:l,metadata:this.client.metadata},expiry:P};await this.client.core.relayer.subscribe(m);const C=await this.sendRequest(m,"wc_sessionSettle",N),{done:O,resolve:b,reject:_}=n.createDelayedPromise();this.events.once(n.engineEvent("session_approve",C),({error:T})=>{T?_(T):b(this.client.session.get(m))});const d=Q(v({},N),{topic:m,acknowledged:!1,self:N.controller,peer:{publicKey:c.publicKey,metadata:c.metadata},controller:l});return await this.client.session.set(m,d),await this.setExpiry(m,P),o&&await this.client.pairing.update(o,{peerMetadata:d.peer.metadata}),o&&t&&(await this.sendResult(t,o,{relay:{protocol:s??"irn"},responderPublicKey:l}),await this.client.proposal.delete(t,n.getSdkError("USER_DISCONNECTED")),await this.activatePairing(o)),{topic:m,acknowledged:O}},this.reject=async e=>{this.isInitialized(),await this.isValidReject(e);const{id:t,reason:s}=e,{pairingTopic:r}=this.client.proposal.get(t);r&&(await this.sendError(t,r,s),await this.client.proposal.delete(t,n.getSdkError("USER_DISCONNECTED")))},this.update=async e=>{this.isInitialized(),await this.isValidUpdate(e);const{topic:t,namespaces:s}=e,r=await this.sendRequest(t,"wc_sessionUpdate",{namespaces:s}),{done:o,resolve:c,reject:h}=n.createDelayedPromise();return this.events.once(n.engineEvent("session_update",r),({error:l})=>{l?h(l):c()}),await this.client.session.update(t,{namespaces:s}),{acknowledged:o}},this.extend=async e=>{this.isInitialized(),await this.isValidExtend(e);const{topic:t}=e,s=await this.sendRequest(t,"wc_sessionExtend",{}),{done:r,resolve:o,reject:c}=n.createDelayedPromise();return this.events.once(n.engineEvent("session_extend",s),({error:h})=>{h?c(h):o()}),await this.setExpiry(t,P),{acknowledged:r}},this.request=async e=>{this.isInitialized(),await this.isValidRequest(e);const{chainId:t,request:s,topic:r}=e,o=await this.sendRequest(r,"wc_sessionRequest",{request:s,chainId:t}),{done:c,resolve:h,reject:l}=n.createDelayedPromise();return this.events.once(n.engineEvent("session_request",o),({error:E,result:m})=>{E?l(E):h(m)}),await c()},this.respond=async e=>{this.isInitialized(),await this.isValidRespond(e);const{topic:t,response:s}=e,{id:r}=s;p.isJsonRpcResult(s)?await this.sendResult(r,t,s.result):p.isJsonRpcError(s)&&await this.sendError(r,t,s.error)},this.ping=async e=>{this.isInitialized(),await this.isValidPing(e);const{topic:t}=e;if(this.client.session.keys.includes(t)){const s=await this.sendRequest(t,"wc_sessionPing",{}),{done:r,resolve:o,reject:c}=n.createDelayedPromise();this.events.once(n.engineEvent("session_ping",s),({error:h})=>{h?c(h):o()}),await r()}else if(this.client.pairing.keys.includes(t)){const s=await this.sendRequest(t,"wc_pairingPing",{}),{done:r,resolve:o,reject:c}=n.createDelayedPromise();this.events.once(n.engineEvent("pairing_ping",s),({error:h})=>{h?c(h):o()}),await r()}},this.emit=async e=>{this.isInitialized(),await this.isValidEmit(e);const{topic:t,event:s,chainId:r}=e;await this.sendRequest(t,"wc_sessionEvent",{event:s,chainId:r})},this.disconnect=async e=>{this.isInitialized(),await this.isValidDisconnect(e);const{topic:t}=e;this.client.session.keys.includes(t)?(await this.sendRequest(t,"wc_sessionDelete",n.getSdkError("USER_DISCONNECTED")),await this.deleteSession(t)):this.client.pairing.keys.includes(t)&&(await this.sendRequest(t,"wc_pairingDelete",n.getSdkError("USER_DISCONNECTED")),await this.deletePairing(t))},this.find=e=>(this.isInitialized(),this.client.session.getAll().filter(t=>n.isSessionCompatible(t,e))),this.activatePairing=async e=>{await this.client.pairing.update(e,{active:!0,expiry:z}),await this.setExpiry(e,z)},this.deleteSession=async e=>{const{self:t}=this.client.session.get(e);await Promise.all([this.client.core.relayer.unsubscribe(e),this.client.session.delete(e,n.getSdkError("USER_DISCONNECTED")),this.client.core.crypto.deleteKeyPair(t.publicKey),this.client.core.crypto.deleteSymKey(e),this.client.expirer.del(e)])},this.deletePairing=async e=>{await Promise.all([this.client.core.relayer.unsubscribe(e),this.client.pairing.delete(e,n.getSdkError("USER_DISCONNECTED")),this.client.core.crypto.deleteSymKey(e),this.client.expirer.del(e)])},this.deleteProposal=async e=>{await Promise.all([this.client.proposal.delete(e,n.getSdkError("USER_DISCONNECTED")),this.client.expirer.del(e)])},this.setExpiry=async(e,t)=>{this.client.pairing.keys.includes(e)?await this.client.pairing.update(e,{expiry:t}):this.client.session.keys.includes(e)&&await this.client.session.update(e,{expiry:t}),this.client.expirer.set(e,t)},this.setProposal=async(e,t)=>{await this.client.proposal.set(e,t),this.client.expirer.set(e,t.expiry)},this.sendRequest=async(e,t,s)=>{const r=p.formatJsonRpcRequest(t,s),o=await this.client.core.crypto.encode(e,r),c=D[t].req;return await this.client.core.relayer.publish(e,o,c),this.client.history.set(e,r),r.id},this.sendResult=async(e,t,s)=>{const r=p.formatJsonRpcResult(e,s),o=await this.client.core.crypto.encode(t,r),c=await this.client.history.get(t,e),h=D[c.request.method].res;await this.client.core.relayer.publish(t,o,h),await this.client.history.resolve(r)},this.sendError=async(e,t,s)=>{const r=p.formatJsonRpcError(e,s),o=await this.client.core.crypto.encode(t,r),c=await this.client.history.get(t,e),h=D[c.request.method].res;await this.client.core.relayer.publish(t,o,h),await this.client.history.resolve(r)},this.cleanup=async()=>{const e=[],t=[],s=[];this.client.session.getAll().forEach(r=>{n.isExpired(r.expiry)&&e.push(r.topic)}),this.client.pairing.getAll().forEach(r=>{n.isExpired(r.expiry)&&t.push(r.topic)}),this.client.proposal.getAll().forEach(r=>{n.isExpired(r.expiry)&&s.push(r.id)}),await Promise.all([...e.map(this.deleteSession),...t.map(this.deletePairing),...s.map(this.deleteProposal)])},this.onRelayEventRequest=e=>{const{topic:t,payload:s}=e,r=s.method;switch(r){case"wc_sessionPropose":return this.onSessionProposeRequest(t,s);case"wc_sessionSettle":return this.onSessionSettleRequest(t,s);case"wc_sessionUpdate":return this.onSessionUpdateRequest(t,s);case"wc_sessionExtend":return this.onSessionExtendRequest(t,s);case"wc_sessionPing":return this.onSessionPingRequest(t,s);case"wc_pairingPing":return this.onPairingPingRequest(t,s);case"wc_sessionDelete":return this.onSessionDeleteRequest(t,s);case"wc_pairingDelete":return this.onPairingDeleteRequest(t,s);case"wc_sessionRequest":return this.onSessionRequest(t,s);case"wc_sessionEvent":return this.onSessionEventRequest(t,s);default:return this.client.logger.info(`Unsupported request method ${r}`)}},this.onRelayEventResponse=async e=>{const{topic:t,payload:s}=e,r=(await this.client.history.get(t,s.id)).request.method;switch(r){case"wc_sessionPropose":return this.onSessionProposeResponse(t,s);case"wc_sessionSettle":return this.onSessionSettleResponse(t,s);case"wc_sessionUpdate":return this.onSessionUpdateResponse(t,s);case"wc_sessionExtend":return this.onSessionExtendResponse(t,s);case"wc_sessionPing":return this.onSessionPingResponse(t,s);case"wc_pairingPing":return this.onPairingPingResponse(t,s);case"wc_sessionRequest":return this.onSessionRequestResponse(t,s);default:return this.client.logger.info(`Unsupported response method ${r}`)}},this.onSessionProposeRequest=async(e,t)=>{const{params:s,id:r}=t;try{this.isValidConnect(v({},t.params));const o=n.calcExpiry(y.FIVE_MINUTES),c=v({id:r,pairingTopic:e,expiry:o},s);await this.setProposal(r,c),this.client.events.emit("session_proposal",{id:r,params:c})}catch(o){await this.sendError(r,e,o),this.client.logger.error(o)}},this.onSessionProposeResponse=async(e,t)=>{const{id:s}=t;if(p.isJsonRpcResult(t)){const{result:r}=t;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:r});const o=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:o});const c=o.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const h=r.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:h});const l=await this.client.core.crypto.generateSharedKey(c,h);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:l});const E=await this.client.core.relayer.subscribe(l);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:E}),await this.activatePairing(e)}else p.isJsonRpcError(t)&&(await this.client.proposal.delete(s,n.getSdkError("USER_DISCONNECTED")),this.events.emit(n.engineEvent("session_connect"),{error:t.error}))},this.onSessionSettleRequest=async(e,t)=>{const{id:s,params:r}=t;try{this.isValidSessionSettleRequest(r);const{relay:o,controller:c,expiry:h,namespaces:l}=t.params,E={topic:e,relay:o,expiry:h,namespaces:l,acknowledged:!0,controller:c.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:c.publicKey,metadata:c.metadata}};await this.sendResult(t.id,e,!0),this.events.emit(n.engineEvent("session_connect"),{session:E})}catch(o){await this.sendError(s,e,o),this.client.logger.error(o)}},this.onSessionSettleResponse=async(e,t)=>{const{id:s}=t;p.isJsonRpcResult(t)?(await this.client.session.update(e,{acknowledged:!0}),this.events.emit(n.engineEvent("session_approve",s),{})):p.isJsonRpcError(t)&&(await this.client.session.delete(e,n.getSdkError("USER_DISCONNECTED")),this.events.emit(n.engineEvent("session_approve",s),{error:t.error}))},this.onSessionUpdateRequest=async(e,t)=>{const{params:s,id:r}=t;try{this.isValidUpdate(v({topic:e},s)),await this.client.session.update(e,{namespaces:s.namespaces}),await this.sendResult(r,e,!0),this.client.events.emit("session_update",{id:r,topic:e,params:s})}catch(o){await this.sendError(r,e,o),this.client.logger.error(o)}},this.onSessionUpdateResponse=(e,t)=>{const{id:s}=t;p.isJsonRpcResult(t)?this.events.emit(n.engineEvent("session_update",s),{}):p.isJsonRpcError(t)&&this.events.emit(n.engineEvent("session_update",s),{error:t.error})},this.onSessionExtendRequest=async(e,t)=>{const{id:s}=t;try{this.isValidExtend({topic:e}),await this.setExpiry(e,P),await this.sendResult(s,e,!0),this.client.events.emit("session_extend",{id:s,topic:e})}catch(r){await this.sendError(s,e,r),this.client.logger.error(r)}},this.onSessionExtendResponse=(e,t)=>{const{id:s}=t;p.isJsonRpcResult(t)?this.events.emit(n.engineEvent("session_extend",s),{}):p.isJsonRpcError(t)&&this.events.emit(n.engineEvent("session_extend",s),{error:t.error})},this.onSessionPingRequest=async(e,t)=>{const{id:s}=t;try{this.isValidPing({topic:e}),await this.sendResult(s,e,!0),this.client.events.emit("session_ping",{id:s,topic:e})}catch(r){await this.sendError(s,e,r),this.client.logger.error(r)}},this.onSessionPingResponse=(e,t)=>{const{id:s}=t;p.isJsonRpcResult(t)?this.events.emit(n.engineEvent("session_ping",s),{}):p.isJsonRpcError(t)&&this.events.emit(n.engineEvent("session_ping",s),{error:t.error})},this.onPairingPingRequest=async(e,t)=>{const{id:s}=t;try{this.isValidPing({topic:e}),await this.sendResult(s,e,!0),this.client.events.emit("pairing_ping",{id:s,topic:e})}catch(r){await this.sendError(s,e,r),this.client.logger.error(r)}},this.onPairingPingResponse=(e,t)=>{const{id:s}=t;p.isJsonRpcResult(t)?this.events.emit(n.engineEvent("pairing_ping",s),{}):p.isJsonRpcError(t)&&this.events.emit(n.engineEvent("pairing_ping",s),{error:t.error})},this.onSessionDeleteRequest=async(e,t)=>{const{id:s}=t;try{this.isValidDisconnect({topic:e,reason:t.params}),await this.sendResult(s,e,!0),await this.deleteSession(e),this.client.events.emit("session_delete",{id:s,topic:e})}catch(r){await this.sendError(s,e,r),this.client.logger.error(r)}},this.onPairingDeleteRequest=async(e,t)=>{const{id:s}=t;try{this.isValidDisconnect({topic:e,reason:t.params}),await this.sendResult(s,e,!0),await this.deletePairing(e),this.client.events.emit("pairing_delete",{id:s,topic:e})}catch(r){await this.sendError(s,e,r),this.client.logger.error(r)}},this.onSessionRequest=async(e,t)=>{const{id:s,params:r}=t;try{this.isValidRequest(v({topic:e},r)),this.client.events.emit("session_request",{id:s,topic:e,params:r})}catch(o){await this.sendError(s,e,o),this.client.logger.error(o)}},this.onSessionRequestResponse=(e,t)=>{const{id:s}=t;p.isJsonRpcResult(t)?this.events.emit(n.engineEvent("session_request",s),{result:t.result}):p.isJsonRpcError(t)&&this.events.emit(n.engineEvent("session_request",s),{error:t.error})},this.onSessionEventRequest=async(e,t)=>{const{id:s,params:r}=t;try{this.isValidEmit(v({topic:e},r)),this.client.events.emit("session_event",{id:s,topic:e,params:r})}catch(o){await this.sendError(s,e,o),this.client.logger.error(o)}},this.isValidConnect=async e=>{if(!n.isValidParams(e)){const{message:c}=n.getInternalError("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(e)}`);throw new Error(c)}const{pairingTopic:t,requiredNamespaces:s,relays:r}=e;n.isUndefined(t)||await this.isValidPairingTopic(t);const o=n.isValidRequiredNamespaces(s,"connect()");if(o)throw new Error(o.message);if(!n.isValidRelays(r,!0)){const{message:c}=n.getInternalError("MISSING_OR_INVALID",`connect() relays: ${r}`);throw new Error(c)}},this.isValidPair=e=>{if(!n.isValidParams(e)){const{message:t}=n.getInternalError("MISSING_OR_INVALID",`pair() params: ${e}`);throw new Error(t)}if(!n.isValidUrl(e.uri)){const{message:t}=n.getInternalError("MISSING_OR_INVALID",`pair() uri: ${e.uri}`);throw new Error(t)}},this.isValidApprove=async e=>{if(!n.isValidParams(e))throw new Error(n.getInternalError("MISSING_OR_INVALID",`approve() params: ${e}`).message);const{id:t,namespaces:s,relayProtocol:r}=e;await this.isValidProposalId(t);const o=this.client.proposal.get(t),c=n.isValidNamespaces(s,"approve()");if(c)throw new Error(c.message);const h=n.isConformingNamespaces(o.requiredNamespaces,s,"update()");if(h)throw new Error(h.message);if(!n.isValidString(r,!0)){const{message:l}=n.getInternalError("MISSING_OR_INVALID",`approve() relayProtocol: ${r}`);throw new Error(l)}},this.isValidReject=async e=>{if(!n.isValidParams(e)){const{message:r}=n.getInternalError("MISSING_OR_INVALID",`reject() params: ${e}`);throw new Error(r)}const{id:t,reason:s}=e;if(await this.isValidProposalId(t),!n.isValidErrorReason(s)){const{message:r}=n.getInternalError("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(s)}`);throw new Error(r)}},this.isValidSessionSettleRequest=e=>{if(!n.isValidParams(e)){const{message:l}=n.getInternalError("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${e}`);throw new Error(l)}const{relay:t,controller:s,namespaces:r,expiry:o}=e;if(!n.isValidRelay(t)){const{message:l}=n.getInternalError("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const c=n.isValidController(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);const h=n.isValidNamespaces(r,"onSessionSettleRequest()");if(h)throw new Error(h.message);if(n.isExpired(o)){const{message:l}=n.getInternalError("EXPIRED","onSessionSettleRequest()");throw new Error(l)}},this.isValidUpdate=async e=>{if(!n.isValidParams(e)){const{message:h}=n.getInternalError("MISSING_OR_INVALID",`update() params: ${e}`);throw new Error(h)}const{topic:t,namespaces:s}=e;await this.isValidSessionTopic(t);const r=this.client.session.get(t),o=n.isValidNamespaces(s,"update()");if(o)throw new Error(o.message);const c=n.isConformingNamespaces(r.requiredNamespaces,s,"update()");if(c)throw new Error(c.message)},this.isValidExtend=async e=>{if(!n.isValidParams(e)){const{message:s}=n.getInternalError("MISSING_OR_INVALID",`extend() params: ${e}`);throw new Error(s)}const{topic:t}=e;await this.isValidSessionTopic(t)},this.isValidRequest=async e=>{if(!n.isValidParams(e)){const{message:c}=n.getInternalError("MISSING_OR_INVALID",`request() params: ${e}`);throw new Error(c)}const{topic:t,request:s,chainId:r}=e;await this.isValidSessionTopic(t);const{namespaces:o}=this.client.session.get(t);if(!n.isValidNamespacesChainId(o,r)){const{message:c}=n.getInternalError("MISSING_OR_INVALID",`request() chainId: ${r}`);throw new Error(c)}if(!n.isValidRequest(s)){const{message:c}=n.getInternalError("MISSING_OR_INVALID",`request() ${JSON.stringify(s)}`);throw new Error(c)}if(!n.isValidNamespacesRequest(o,r,s.method)){const{message:c}=n.getInternalError("MISSING_OR_INVALID",`request() method: ${s.method}`);throw new Error(c)}},this.isValidRespond=async e=>{if(!n.isValidParams(e)){const{message:r}=n.getInternalError("MISSING_OR_INVALID",`respond() params: ${e}`);throw new Error(r)}const{topic:t,response:s}=e;if(await this.isValidSessionTopic(t),!n.isValidResponse(s)){const{message:r}=n.getInternalError("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(r)}},this.isValidPing=async e=>{if(!n.isValidParams(e)){const{message:s}=n.getInternalError("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(s)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)},this.isValidEmit=async e=>{if(!n.isValidParams(e)){const{message:c}=n.getInternalError("MISSING_OR_INVALID",`emit() params: ${e}`);throw new Error(c)}const{topic:t,event:s,chainId:r}=e;await this.isValidSessionTopic(t);const{namespaces:o}=this.client.session.get(t);if(!n.isValidNamespacesChainId(o,r)){const{message:c}=n.getInternalError("MISSING_OR_INVALID",`emit() chainId: ${r}`);throw new Error(c)}if(!n.isValidEvent(s)){const{message:c}=n.getInternalError("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(c)}if(!n.isValidNamespacesEvent(o,r,s.name)){const{message:c}=n.getInternalError("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(c)}},this.isValidDisconnect=async e=>{if(!n.isValidParams(e)){const{message:s}=n.getInternalError("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(s)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)}}async createPairing(){const i=n.generateRandomBytes32(),e=await this.client.core.crypto.setSymKey(i),t=n.calcExpiry(y.FIVE_MINUTES),s={protocol:R.RELAYER_DEFAULT_PROTOCOL},r={topic:e,expiry:t,relay:s,active:!1},o=n.formatUri({protocol:this.client.protocol,version:this.client.version,topic:e,symKey:i,relay:s});return await this.client.pairing.set(e,r),await this.client.core.relayer.subscribe(e),await this.setExpiry(e,t),{topic:e,uri:o}}isInitialized(){if(!this.initialized){const{message:i}=n.getInternalError("NOT_INITIALIZED",this.name);throw new Error(i)}}registerRelayerEvents(){this.client.core.relayer.on(R.RELAYER_EVENTS.message,async i=>{const{topic:e,message:t}=i,s=await this.client.core.crypto.decode(e,t);p.isJsonRpcRequest(s)?(this.client.history.set(e,s),this.onRelayEventRequest({topic:e,payload:s})):p.isJsonRpcResponse(s)&&(await this.client.history.resolve(s),this.onRelayEventResponse({topic:e,payload:s}))})}registerExpirerEvents(){this.client.expirer.on(u.expired,async i=>{const{topic:e,id:t}=n.parseExpirerTarget(i.target);e?this.client.session.keys.includes(e)?(await this.deleteSession(e),this.client.events.emit("session_expire",{topic:e})):this.client.pairing.keys.includes(e)&&(await this.deletePairing(e),this.client.events.emit("pairing_expire",{topic:e})):t&&await this.deleteProposal(t)})}async isValidPairingTopic(i){if(!n.isValidString(i,!1)){const{message:e}=n.getInternalError("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(e)}if(!this.client.pairing.keys.includes(i)){const{message:e}=n.getInternalError("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(e)}if(n.isExpired(this.client.pairing.get(i).expiry)){await this.deletePairing(i);const{message:e}=n.getInternalError("EXPIRED",`pairing topic: ${i}`);throw new Error(e)}}async isValidSessionTopic(i){if(!n.isValidString(i,!1)){const{message:e}=n.getInternalError("MISSING_OR_INVALID",`session topic should be a string: ${i}`);throw new Error(e)}if(!this.client.session.keys.includes(i)){const{message:e}=n.getInternalError("NO_MATCHING_KEY",`session topic doesn't exist: ${i}`);throw new Error(e)}if(n.isExpired(this.client.session.get(i).expiry)){await this.deleteSession(i);const{message:e}=n.getInternalError("EXPIRED",`session topic: ${i}`);throw new Error(e)}}async isValidSessionOrPairingTopic(i){if(this.client.session.keys.includes(i))await this.isValidSessionTopic(i);else if(this.client.pairing.keys.includes(i))await this.isValidPairingTopic(i);else if(n.isValidString(i,!1)){const{message:e}=n.getInternalError("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${i}`);throw new Error(e)}else{const{message:e}=n.getInternalError("MISSING_OR_INVALID",`session or pairing topic should be a string: ${i}`);throw new Error(e)}}async isValidProposalId(i){if(!n.isValidId(i)){const{message:e}=n.getInternalError("MISSING_OR_INVALID",`proposal id should be a number: ${i}`);throw new Error(e)}if(!this.client.proposal.keys.includes(i)){const{message:e}=n.getInternalError("NO_MATCHING_KEY",`proposal id doesn't exist: ${i}`);throw new Error(e)}if(n.isExpired(this.client.proposal.get(i).expiry)){await this.deleteProposal(i);const{message:e}=n.getInternalError("EXPIRED",`proposal id: ${i}`);throw new Error(e)}}}class Ee extends V.IExpirer{constructor(i,e){super(i,e),this.core=i,this.logger=e,this.expirations=new Map,this.events=new L.EventEmitter,this.name=k,this.version=K,this.cached=[],this.initialized=!1,this.storagePrefix=f,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(t=>this.expirations.set(t.target,t)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=t=>{try{const s=this.formatTarget(t);return typeof this.getExpiration(s)<"u"}catch{return!1}},this.set=(t,s)=>{this.isInitialized();const r=this.formatTarget(t),o={target:r,expiry:s};this.expirations.set(r,o),this.checkExpiry(r,o),this.events.emit(u.created,{target:r,expiration:o})},this.get=t=>{this.isInitialized();const s=this.formatTarget(t);return this.getExpiration(s)},this.del=t=>{this.isInitialized();const s=this.formatTarget(t);if(this.has(s)){const r=this.getExpiration(s);this.expirations.delete(s),this.events.emit(u.deleted,{target:s,expiration:r})}},this.on=(t,s)=>{this.events.on(t,s)},this.once=(t,s)=>{this.events.once(t,s)},this.off=(t,s)=>{this.events.off(t,s)},this.removeListener=(t,s)=>{this.events.removeListener(t,s)},this.logger=S.generateChildLogger(e,this.name)}get context(){return S.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(i){if(typeof i=="string")return n.formatTopicTarget(i);if(typeof i=="number")return n.formatIdTarget(i);const{message:e}=n.getInternalError("UNKNOWN_TYPE",`Target type: ${typeof i}`);throw new Error(e)}async setExpirations(i){await this.core.storage.setItem(this.storageKey,i)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(u.sync)}async restore(){try{const i=await this.getExpirations();if(typeof i>"u"||!i.length)return;if(this.expirations.size){const{message:e}=n.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}this.cached=i,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(i){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(i)}}getExpiration(i){const e=this.expirations.get(i);if(!e){const{message:t}=n.getInternalError("NO_MATCHING_KEY",`${this.name}: ${i}`);throw this.logger.error(t),new Error(t)}return e}checkExpiry(i,e){const{expiry:t}=e;y.toMiliseconds(t)-Date.now()<=0&&this.expire(i,e)}expire(i,e){this.expirations.delete(i),this.events.emit(u.expired,{target:i,expiration:e})}checkExpirations(){this.expirations.forEach((i,e)=>this.checkExpiry(e,i))}registerEventListeners(){this.core.heartbeat.on(te.HEARTBEAT_EVENTS.pulse,()=>this.checkExpirations()),this.events.on(u.created,i=>{const e=u.created;this.logger.info(`Emitting ${e}`),this.logger.debug({type:"event",event:e,data:i}),this.persist()}),this.events.on(u.expired,i=>{const e=u.expired;this.logger.info(`Emitting ${e}`),this.logger.debug({type:"event",event:e,data:i}),this.persist()}),this.events.on(u.deleted,i=>{const e=u.deleted;this.logger.info(`Emitting ${e}`),this.logger.debug({type:"event",event:e,data:i}),this.persist()})}isInitialized(){if(!this.initialized){const{message:i}=n.getInternalError("NOT_INITIALIZED",this.name);throw new Error(i)}}}class me extends V.IJsonRpcHistory{constructor(i,e){super(i,e),this.core=i,this.logger=e,this.records=new Map,this.events=new L.EventEmitter,this.name=J,this.version=X,this.cached=[],this.initialized=!1,this.storagePrefix=f,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(t=>this.records.set(t.id,t)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(t,s,r)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:t,request:s,chainId:r}),this.records.has(s.id))return;const o={id:s.id,topic:t,request:{method:s.method,params:s.params||null},chainId:r};this.records.set(o.id,o),this.events.emit(w.created,o)},this.resolve=async t=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:t}),!this.records.has(t.id))return;const s=await this.getRecord(t.id);typeof s.response>"u"&&(s.response=p.isJsonRpcError(t)?{error:t.error}:{result:t.result},this.records.set(s.id,s),this.events.emit(w.updated,s))},this.get=async(t,s)=>{this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:t,id:s});const r=await this.getRecord(s);if(r.topic!==t){const{message:o}=n.getInternalError("MISMATCHED_TOPIC",`${this.name}, ${s}`);throw this.logger.error(o),new Error(o)}return r},this.delete=(t,s)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:s}),this.values.forEach(r=>{if(r.topic===t){if(typeof s<"u"&&r.id!==s)return;this.records.delete(r.id),this.events.emit(w.deleted,r)}})},this.exists=async(t,s)=>(this.isInitialized(),this.records.has(s)?(await this.getRecord(s)).topic===t:!1),this.on=(t,s)=>{this.events.on(t,s)},this.once=(t,s)=>{this.events.once(t,s)},this.off=(t,s)=>{this.events.off(t,s)},this.removeListener=(t,s)=>{this.events.removeListener(t,s)},this.logger=S.generateChildLogger(e,this.name)}get context(){return S.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const i=[];return this.values.forEach(e=>{if(typeof e.response<"u")return;const t={topic:e.topic,request:p.formatJsonRpcRequest(e.request.method,e.request.params,e.id),chainId:e.chainId};return i.push(t)}),i}async setJsonRpcRecords(i){await this.core.storage.setItem(this.storageKey,i)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(i){this.isInitialized();const e=this.records.get(i);if(!e){const{message:t}=n.getInternalError("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(t)}return e}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(w.sync)}async restore(){try{const i=await this.getJsonRpcRecords();if(typeof i>"u"||!i.length)return;if(this.records.size){const{message:e}=n.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}this.cached=i,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}}registerEventListeners(){this.events.on(w.created,i=>{const e=w.created;this.logger.info(`Emitting ${e}`),this.logger.debug({type:"event",event:e,record:i}),this.persist()}),this.events.on(w.updated,i=>{const e=w.updated;this.logger.info(`Emitting ${e}`),this.logger.debug({type:"event",event:e,record:i}),this.persist()}),this.events.on(w.deleted,i=>{const e=w.deleted;this.logger.info(`Emitting ${e}`),this.logger.debug({type:"event",event:e,record:i}),this.persist()})}isInitialized(){if(!this.initialized){const{message:i}=n.getInternalError("NOT_INITIALIZED",this.name);throw new Error(i)}}}class we extends R.Store{constructor(i,e){super(i,e,j,f),this.core=i,this.logger=e}}class ye extends R.Store{constructor(i,e){super(i,e,Y,f),this.core=i,this.logger=e}}class Ie extends R.Store{constructor(i,e){super(i,e,F,f),this.core=i,this.logger=e}}class A extends V.ISignClient{constructor(i){super(i),this.protocol=G,this.version=$,this.name=q.name,this.events=new L.EventEmitter,this.on=(t,s)=>this.events.on(t,s),this.once=(t,s)=>this.events.once(t,s),this.off=(t,s)=>this.events.off(t,s),this.removeListener=(t,s)=>this.events.removeListener(t,s),this.connect=async t=>{try{return await this.engine.connect(t)}catch(s){throw this.logger.error(s.message),s}},this.pair=async t=>{try{return await this.engine.pair(t)}catch(s){throw this.logger.error(s.message),s}},this.approve=async t=>{try{return await this.engine.approve(t)}catch(s){throw this.logger.error(s.message),s}},this.reject=async t=>{try{return await this.engine.reject(t)}catch(s){throw this.logger.error(s.message),s}},this.update=async t=>{try{return await this.engine.update(t)}catch(s){throw this.logger.error(s.message),s}},this.extend=async t=>{try{return await this.engine.extend(t)}catch(s){throw this.logger.error(s.message),s}},this.request=async t=>{try{return await this.engine.request(t)}catch(s){throw this.logger.error(s.message),s}},this.respond=async t=>{try{return await this.engine.respond(t)}catch(s){throw this.logger.error(s.message),s}},this.ping=async t=>{try{return await this.engine.ping(t)}catch(s){throw this.logger.error(s.message),s}},this.emit=async t=>{try{return await this.engine.emit(t)}catch(s){throw this.logger.error(s.message),s}},this.disconnect=async t=>{try{return await this.engine.disconnect(t)}catch(s){throw this.logger.error(s.message),s}},this.find=t=>{try{return this.engine.find(t)}catch(s){throw this.logger.error(s.message),s}},this.name=i?.name||q.name,this.metadata=i?.metadata||n.getAppMetadata();const e=typeof i?.logger<"u"&&typeof i?.logger!="string"?i.logger:ie.default(S.getDefaultLoggerOptions({level:i?.logger||q.logger}));this.core=i?.core||new R.Core(i),this.logger=S.generateChildLogger(e,this.name),this.pairing=new we(this.core,this.logger),this.session=new Ie(this.core,this.logger),this.proposal=new ye(this.core,this.logger),this.history=new me(this.core,this.logger),this.expirer=new Ee(this.core,this.logger),this.engine=new ue(this)}static async init(i){const e=new A(i);return await e.initialize(),e}get context(){return S.getLoggerContext(this.logger)}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.pairing.init(),await this.session.init(),await this.proposal.init(),await this.history.init(),await this.expirer.init(),await this.engine.init(),this.logger.info("SignClient Initilization Success")}catch(i){throw this.logger.info("SignClient Initilization Failure"),this.logger.error(i.message),i}}}const _e=A;exports.ENGINE_CONTEXT=W,exports.ENGINE_RPC_OPTS=D,exports.EXPIRER_CONTEXT=k,exports.EXPIRER_DEFAULT_TTL=ae,exports.EXPIRER_EVENTS=u,exports.EXPIRER_STORAGE_VERSION=K,exports.HISTORY_CONTEXT=J,exports.HISTORY_EVENTS=w,exports.HISTORY_STORAGE_VERSION=X,exports.PAIRING_CONTEXT=j,exports.PAIRING_DEFAULT_TTL=ce,exports.PROPOSAL_CONTEXT=Y,exports.PROPOSAL_EXPIRY=z,exports.SESSION_CONTEXT=F,exports.SESSION_DEFAULT_TTL=H,exports.SESSION_EXPIRY=P,exports.SIGN_CLIENT_CONTEXT=M,exports.SIGN_CLIENT_DEFAULT=q,exports.SIGN_CLIENT_EVENTS=ne,exports.SIGN_CLIENT_PROTOCOL=G,exports.SIGN_CLIENT_STORAGE_OPTIONS=oe,exports.SIGN_CLIENT_STORAGE_PREFIX=f,exports.SIGN_CLIENT_VERSION=$,exports.SignClient=_e,exports.default=A;
//# sourceMappingURL=index.cjs.js.map

@@ -1,2 +0,2 @@

import{RELAYER_DEFAULT_PROTOCOL as W,RELAYER_EVENTS as ue,Store as U,Core as me}from"@walletconnect/core";import{generateChildLogger as k,getLoggerContext as j,getDefaultLoggerOptions as we}from"@walletconnect/logger";import{IEngine as ye,IExpirer as Ee,IJsonRpcHistory as _e,ISignClient as fe}from"@walletconnect/types";import{calcExpiry as P,createDelayedPromise as N,engineEvent as p,getInternalError as c,parseUri as Ie,getSdkError as _,isSessionCompatible as ve,isExpired as x,isValidParams as u,isUndefined as Se,isValidRequiredNamespaces as Re,isValidRelays as Ne,isValidUrl as xe,isValidNamespaces as J,isConformingNamespaces as Z,isValidString as b,isValidErrorReason as Pe,isValidRelay as Te,isValidController as Oe,isValidNamespacesChainId as B,isValidRequest as Ve,isValidNamespacesRequest as qe,isValidResponse as Le,isValidEvent as De,isValidNamespacesEvent as be,generateRandomBytes32 as Ae,formatUri as Ce,parseExpirerTarget as $e,isValidId as Ge,formatTopicTarget as ze,formatIdTarget as Me,getAppMetadata as Ke}from"@walletconnect/utils";import Ue from"pino";import{ONE_DAY as ke,THIRTY_DAYS as Q,SEVEN_DAYS as je,FIVE_MINUTES as A,toMiliseconds as Je}from"@walletconnect/time";import{isJsonRpcResult as S,isJsonRpcError as f,formatJsonRpcRequest as ee,formatJsonRpcResult as Ye,formatJsonRpcError as Xe,isJsonRpcRequest as He,isJsonRpcResponse as Fe}from"@walletconnect/jsonrpc-utils";import{HEARTBEAT_EVENTS as We}from"@walletconnect/heartbeat";function d(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}var C=d;d.EventEmitter=d,d.prototype._events=void 0,d.prototype._maxListeners=void 0,d.defaultMaxListeners=10,d.prototype.setMaxListeners=function(o){if(!Ze(o)||o<0||isNaN(o))throw TypeError("n must be a positive number");return this._maxListeners=o,this},d.prototype.emit=function(o){var i,e,t,s,r,n;if(this._events||(this._events={}),o==="error"&&(!this._events.error||q(this._events.error)&&!this._events.error.length)){if(i=arguments[1],i instanceof Error)throw i;var a=new Error('Uncaught, unspecified "error" event. ('+i+")");throw a.context=i,a}if(e=this._events[o],te(e))return!1;if(I(e))switch(arguments.length){case 1:e.call(this);break;case 2:e.call(this,arguments[1]);break;case 3:e.call(this,arguments[1],arguments[2]);break;default:s=Array.prototype.slice.call(arguments,1),e.apply(this,s)}else if(q(e))for(s=Array.prototype.slice.call(arguments,1),n=e.slice(),t=n.length,r=0;r<t;r++)n[r].apply(this,s);return!0},d.prototype.addListener=function(o,i){var e;if(!I(i))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",o,I(i.listener)?i.listener:i),this._events[o]?q(this._events[o])?this._events[o].push(i):this._events[o]=[this._events[o],i]:this._events[o]=i,q(this._events[o])&&!this._events[o].warned&&(te(this._maxListeners)?e=d.defaultMaxListeners:e=this._maxListeners,e&&e>0&&this._events[o].length>e&&(this._events[o].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[o].length),typeof console.trace=="function"&&console.trace())),this},d.prototype.on=d.prototype.addListener,d.prototype.once=function(o,i){if(!I(i))throw TypeError("listener must be a function");var e=!1;function t(){this.removeListener(o,t),e||(e=!0,i.apply(this,arguments))}return t.listener=i,this.on(o,t),this},d.prototype.removeListener=function(o,i){var e,t,s,r;if(!I(i))throw TypeError("listener must be a function");if(!this._events||!this._events[o])return this;if(e=this._events[o],s=e.length,t=-1,e===i||I(e.listener)&&e.listener===i)delete this._events[o],this._events.removeListener&&this.emit("removeListener",o,i);else if(q(e)){for(r=s;r-- >0;)if(e[r]===i||e[r].listener&&e[r].listener===i){t=r;break}if(t<0)return this;e.length===1?(e.length=0,delete this._events[o]):e.splice(t,1),this._events.removeListener&&this.emit("removeListener",o,i)}return this},d.prototype.removeAllListeners=function(o){var i,e;if(!this._events)return this;if(!this._events.removeListener)return arguments.length===0?this._events={}:this._events[o]&&delete this._events[o],this;if(arguments.length===0){for(i in this._events)i!=="removeListener"&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events={},this}if(e=this._events[o],I(e))this.removeListener(o,e);else if(e)for(;e.length;)this.removeListener(o,e[e.length-1]);return delete this._events[o],this},d.prototype.listeners=function(o){var i;return!this._events||!this._events[o]?i=[]:I(this._events[o])?i=[this._events[o]]:i=this._events[o].slice(),i},d.prototype.listenerCount=function(o){if(this._events){var i=this._events[o];if(I(i))return 1;if(i)return i.length}return 0},d.listenerCount=function(o,i){return o.listenerCount(i)};function I(o){return typeof o=="function"}function Ze(o){return typeof o=="number"}function q(o){return typeof o=="object"&&o!==null}function te(o){return o===void 0}const Y="wc",X=2,H="client",T=`${Y}@${X}:${H}:`,$={name:H,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},Be={session_proposal:"session_proposal",session_update:"session_update",session_extend:"session_extend",session_ping:"session_ping",pairing_ping:"pairing_ping",session_delete:"session_delete",session_expire:"session_expire",pairing_delete:"pairing_delete",pairing_expire:"pairing_expire",session_request:"session_request",session_event:"session_event",proposal_expire:"proposal_expire"},Qe={database:":memory:"},se="expirer",m={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},ie="0.3",et=ke,E={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},re="history",ne="0.3",oe="pairing",tt=Q,ae="proposal",F=P(Q),ce="session",he=je,L=P(he),le="engine",G={wc_pairingDelete:{req:{prompt:!1,tag:1e3},res:{prompt:!1,tag:1001}},wc_pairingPing:{req:{prompt:!1,tag:1002},res:{prompt:!1,tag:1003}},wc_sessionPropose:{req:{prompt:!0,tag:1100},res:{prompt:!1,tag:1101}},wc_sessionSettle:{req:{prompt:!1,tag:1102},res:{prompt:!1,tag:1103}},wc_sessionUpdate:{req:{prompt:!1,tag:1104},res:{prompt:!1,tag:1105}},wc_sessionExtend:{req:{prompt:!1,tag:1106},res:{prompt:!1,tag:1107}},wc_sessionRequest:{req:{prompt:!0,tag:1108},res:{prompt:!1,tag:1109}},wc_sessionEvent:{req:{prompt:!0,tag:1110},res:{prompt:!1,tag:1111}},wc_sessionDelete:{req:{prompt:!1,tag:1112},res:{prompt:!1,tag:1113}},wc_sessionPing:{req:{prompt:!1,tag:1114},res:{prompt:!1,tag:1115}}};var st=Object.defineProperty,it=Object.defineProperties,rt=Object.getOwnPropertyDescriptors,pe=Object.getOwnPropertySymbols,nt=Object.prototype.hasOwnProperty,ot=Object.prototype.propertyIsEnumerable,de=(o,i,e)=>i in o?st(o,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[i]=e,R=(o,i)=>{for(var e in i||(i={}))nt.call(i,e)&&de(o,e,i[e]);if(pe)for(var e of pe(i))ot.call(i,e)&&de(o,e,i[e]);return o},ge=(o,i)=>it(o,rt(i));class at extends ye{constructor(i){super(i),this.events=new C,this.initialized=!1,this.name=le,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0)},this.connect=async e=>{this.isInitialized(),await this.isValidConnect(e);const{pairingTopic:t,requiredNamespaces:s,relays:r}=e;let n=t,a,h=!1;if(n&&(h=this.client.pairing.get(n).active),!n||!h){const{topic:v,uri:g}=await this.createPairing();n=v,a=g}const l=await this.client.core.crypto.generateKeyPair(),w={requiredNamespaces:s,relays:r??[{protocol:W}],proposer:{publicKey:l,metadata:this.client.metadata}},{reject:y,resolve:O,done:M}=N();if(this.events.once(p("session_connect"),async({error:v,session:g})=>{if(v)y(v);else if(g){g.self.publicKey=l;const V=ge(R({},g),{requiredNamespaces:s});await this.client.session.set(g.topic,V),await this.setExpiry(g.topic,g.expiry),n&&await this.client.pairing.update(n,{peerMetadata:g.peer.metadata}),O(V)}}),!n){const{message:v}=c("NO_MATCHING_KEY",`connect() pairing topic: ${n}`);throw new Error(v)}const D=await this.sendRequest(n,"wc_sessionPropose",w),K=P(A);return await this.setProposal(D,R({id:D,expiry:K},w)),{uri:a,approval:M}},this.pair=async e=>{this.isInitialized(),this.isValidPair(e);const{topic:t,symKey:s,relay:r}=Ie(e.uri),n=P(A),a={topic:t,relay:r,expiry:n,active:!1};return await this.client.pairing.set(t,a),await this.client.core.crypto.setSymKey(s,t),await this.client.core.relayer.subscribe(t,{relay:r}),await this.setExpiry(t,n),a},this.approve=async e=>{this.isInitialized(),await this.isValidApprove(e);const{id:t,relayProtocol:s,namespaces:r}=e,{pairingTopic:n,proposer:a,requiredNamespaces:h}=this.client.proposal.get(t),l=await this.client.core.crypto.generateKeyPair(),w=a.publicKey,y=await this.client.core.crypto.generateSharedKey(l,w),O={relay:{protocol:s??"iridium"},namespaces:r,requiredNamespaces:h,controller:{publicKey:l,metadata:this.client.metadata},expiry:L};await this.client.core.relayer.subscribe(y);const M=await this.sendRequest(y,"wc_sessionSettle",O),{done:D,resolve:K,reject:v}=N();this.events.once(p("session_approve",M),({error:V})=>{V?v(V):K(this.client.session.get(y))});const g=ge(R({},O),{topic:y,acknowledged:!1,self:O.controller,peer:{publicKey:a.publicKey,metadata:a.metadata},controller:l});return await this.client.session.set(y,g),await this.setExpiry(y,L),n&&await this.client.pairing.update(n,{peerMetadata:g.peer.metadata}),n&&t&&(await this.sendResult(t,n,{relay:{protocol:s??"iridium"},responderPublicKey:l}),await this.client.proposal.delete(t,_("USER_DISCONNECTED")),await this.activatePairing(n)),{topic:y,acknowledged:D}},this.reject=async e=>{this.isInitialized(),await this.isValidReject(e);const{id:t,reason:s}=e,{pairingTopic:r}=this.client.proposal.get(t);r&&(await this.sendError(t,r,s),await this.client.proposal.delete(t,_("USER_DISCONNECTED")))},this.update=async e=>{this.isInitialized(),await this.isValidUpdate(e);const{topic:t,namespaces:s}=e,r=await this.sendRequest(t,"wc_sessionUpdate",{namespaces:s}),{done:n,resolve:a,reject:h}=N();return this.events.once(p("session_update",r),({error:l})=>{l?h(l):a()}),await this.client.session.update(t,{namespaces:s}),{acknowledged:n}},this.extend=async e=>{this.isInitialized(),await this.isValidExtend(e);const{topic:t}=e,s=await this.sendRequest(t,"wc_sessionExtend",{}),{done:r,resolve:n,reject:a}=N();return this.events.once(p("session_extend",s),({error:h})=>{h?a(h):n()}),await this.setExpiry(t,L),{acknowledged:r}},this.request=async e=>{this.isInitialized(),await this.isValidRequest(e);const{chainId:t,request:s,topic:r}=e,n=await this.sendRequest(r,"wc_sessionRequest",{request:s,chainId:t}),{done:a,resolve:h,reject:l}=N();return this.events.once(p("session_request",n),({error:w,result:y})=>{w?l(w):h(y)}),await a()},this.respond=async e=>{this.isInitialized(),await this.isValidRespond(e);const{topic:t,response:s}=e,{id:r}=s;S(s)?await this.sendResult(r,t,s.result):f(s)&&await this.sendError(r,t,s.error)},this.ping=async e=>{this.isInitialized(),await this.isValidPing(e);const{topic:t}=e;if(this.client.session.keys.includes(t)){const s=await this.sendRequest(t,"wc_sessionPing",{}),{done:r,resolve:n,reject:a}=N();this.events.once(p("session_ping",s),({error:h})=>{h?a(h):n()}),await r()}else if(this.client.pairing.keys.includes(t)){const s=await this.sendRequest(t,"wc_pairingPing",{}),{done:r,resolve:n,reject:a}=N();this.events.once(p("pairing_ping",s),({error:h})=>{h?a(h):n()}),await r()}},this.emit=async e=>{this.isInitialized(),await this.isValidEmit(e);const{topic:t,event:s,chainId:r}=e;await this.sendRequest(t,"wc_sessionEvent",{event:s,chainId:r})},this.disconnect=async e=>{this.isInitialized(),await this.isValidDisconnect(e);const{topic:t}=e;this.client.session.keys.includes(t)?(await this.sendRequest(t,"wc_sessionDelete",_("USER_DISCONNECTED")),await this.deleteSession(t)):this.client.pairing.keys.includes(t)&&(await this.sendRequest(t,"wc_pairingDelete",_("USER_DISCONNECTED")),await this.deletePairing(t))},this.find=e=>(this.isInitialized(),this.client.session.getAll().filter(t=>ve(t,e))),this.activatePairing=async e=>{await this.client.pairing.update(e,{active:!0,expiry:F}),await this.setExpiry(e,F)},this.deleteSession=async e=>{const{self:t}=this.client.session.get(e);await Promise.all([this.client.core.relayer.unsubscribe(e),this.client.session.delete(e,_("USER_DISCONNECTED")),this.client.core.crypto.deleteKeyPair(t.publicKey),this.client.core.crypto.deleteSymKey(e),this.client.expirer.del(e)])},this.deletePairing=async e=>{await Promise.all([this.client.core.relayer.unsubscribe(e),this.client.pairing.delete(e,_("USER_DISCONNECTED")),this.client.core.crypto.deleteSymKey(e),this.client.expirer.del(e)])},this.deleteProposal=async e=>{await Promise.all([this.client.proposal.delete(e,_("USER_DISCONNECTED")),this.client.expirer.del(e)])},this.setExpiry=async(e,t)=>{this.client.pairing.keys.includes(e)?await this.client.pairing.update(e,{expiry:t}):this.client.session.keys.includes(e)&&await this.client.session.update(e,{expiry:t}),this.client.expirer.set(e,t)},this.setProposal=async(e,t)=>{await this.client.proposal.set(e,t),this.client.expirer.set(e,t.expiry)},this.sendRequest=async(e,t,s)=>{const r=ee(t,s),n=await this.client.core.crypto.encode(e,r),a=G[t].req;return await this.client.core.relayer.publish(e,n,a),this.client.history.set(e,r),r.id},this.sendResult=async(e,t,s)=>{const r=Ye(e,s),n=await this.client.core.crypto.encode(t,r),a=await this.client.history.get(t,e),h=G[a.request.method].res;await this.client.core.relayer.publish(t,n,h),await this.client.history.resolve(r)},this.sendError=async(e,t,s)=>{const r=Xe(e,s),n=await this.client.core.crypto.encode(t,r),a=await this.client.history.get(t,e),h=G[a.request.method].res;await this.client.core.relayer.publish(t,n,h),await this.client.history.resolve(r)},this.cleanup=async()=>{const e=[],t=[],s=[];this.client.session.getAll().forEach(r=>{x(r.expiry)&&e.push(r.topic)}),this.client.pairing.getAll().forEach(r=>{x(r.expiry)&&t.push(r.topic)}),this.client.proposal.getAll().forEach(r=>{x(r.expiry)&&s.push(r.id)}),await Promise.all([...e.map(this.deleteSession),...t.map(this.deletePairing),...s.map(this.deleteProposal)])},this.onRelayEventRequest=e=>{const{topic:t,payload:s}=e,r=s.method;switch(r){case"wc_sessionPropose":return this.onSessionProposeRequest(t,s);case"wc_sessionSettle":return this.onSessionSettleRequest(t,s);case"wc_sessionUpdate":return this.onSessionUpdateRequest(t,s);case"wc_sessionExtend":return this.onSessionExtendRequest(t,s);case"wc_sessionPing":return this.onSessionPingRequest(t,s);case"wc_pairingPing":return this.onPairingPingRequest(t,s);case"wc_sessionDelete":return this.onSessionDeleteRequest(t,s);case"wc_pairingDelete":return this.onPairingDeleteRequest(t,s);case"wc_sessionRequest":return this.onSessionRequest(t,s);case"wc_sessionEvent":return this.onSessionEventRequest(t,s);default:return this.client.logger.info(`Unsupported request method ${r}`)}},this.onRelayEventResponse=async e=>{const{topic:t,payload:s}=e,r=(await this.client.history.get(t,s.id)).request.method;switch(r){case"wc_sessionPropose":return this.onSessionProposeResponse(t,s);case"wc_sessionSettle":return this.onSessionSettleResponse(t,s);case"wc_sessionUpdate":return this.onSessionUpdateResponse(t,s);case"wc_sessionExtend":return this.onSessionExtendResponse(t,s);case"wc_sessionPing":return this.onSessionPingResponse(t,s);case"wc_pairingPing":return this.onPairingPingResponse(t,s);case"wc_sessionRequest":return this.onSessionRequestResponse(t,s);default:return this.client.logger.info(`Unsupported response method ${r}`)}},this.onSessionProposeRequest=async(e,t)=>{const{params:s,id:r}=t;try{this.isValidConnect(R({},t.params));const n=P(A),a=R({id:r,pairingTopic:e,expiry:n},s);await this.setProposal(r,a),this.client.events.emit("session_proposal",{id:r,params:a})}catch(n){await this.sendError(r,e,n),this.client.logger.error(n)}},this.onSessionProposeResponse=async(e,t)=>{const{id:s}=t;if(S(t)){const{result:r}=t;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:r});const n=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:n});const a=n.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:a});const h=r.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:h});const l=await this.client.core.crypto.generateSharedKey(a,h);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:l});const w=await this.client.core.relayer.subscribe(l);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:w}),await this.activatePairing(e)}else f(t)&&(await this.client.proposal.delete(s,_("USER_DISCONNECTED")),this.events.emit(p("session_connect"),{error:t.error}))},this.onSessionSettleRequest=async(e,t)=>{const{id:s,params:r}=t;try{this.isValidSessionSettleRequest(r);const{relay:n,controller:a,expiry:h,namespaces:l}=t.params,w={topic:e,relay:n,expiry:h,namespaces:l,acknowledged:!0,controller:a.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}};await this.sendResult(t.id,e,!0),this.events.emit(p("session_connect"),{session:w})}catch(n){await this.sendError(s,e,n),this.client.logger.error(n)}},this.onSessionSettleResponse=async(e,t)=>{const{id:s}=t;S(t)?(await this.client.session.update(e,{acknowledged:!0}),this.events.emit(p("session_approve",s),{})):f(t)&&(await this.client.session.delete(e,_("USER_DISCONNECTED")),this.events.emit(p("session_approve",s),{error:t.error}))},this.onSessionUpdateRequest=async(e,t)=>{const{params:s,id:r}=t;try{this.isValidUpdate(R({topic:e},s)),await this.client.session.update(e,{namespaces:s.namespaces}),await this.sendResult(r,e,!0),this.client.events.emit("session_update",{id:r,topic:e,params:s})}catch(n){await this.sendError(r,e,n),this.client.logger.error(n)}},this.onSessionUpdateResponse=(e,t)=>{const{id:s}=t;S(t)?this.events.emit(p("session_update",s),{}):f(t)&&this.events.emit(p("session_update",s),{error:t.error})},this.onSessionExtendRequest=async(e,t)=>{const{id:s}=t;try{this.isValidExtend({topic:e}),await this.setExpiry(e,L),await this.sendResult(s,e,!0),this.client.events.emit("session_extend",{id:s,topic:e})}catch(r){await this.sendError(s,e,r),this.client.logger.error(r)}},this.onSessionExtendResponse=(e,t)=>{const{id:s}=t;S(t)?this.events.emit(p("session_extend",s),{}):f(t)&&this.events.emit(p("session_extend",s),{error:t.error})},this.onSessionPingRequest=async(e,t)=>{const{id:s}=t;try{this.isValidPing({topic:e}),await this.sendResult(s,e,!0),this.client.events.emit("session_ping",{id:s,topic:e})}catch(r){await this.sendError(s,e,r),this.client.logger.error(r)}},this.onSessionPingResponse=(e,t)=>{const{id:s}=t;S(t)?this.events.emit(p("session_ping",s),{}):f(t)&&this.events.emit(p("session_ping",s),{error:t.error})},this.onPairingPingRequest=async(e,t)=>{const{id:s}=t;try{this.isValidPing({topic:e}),await this.sendResult(s,e,!0),this.client.events.emit("pairing_ping",{id:s,topic:e})}catch(r){await this.sendError(s,e,r),this.client.logger.error(r)}},this.onPairingPingResponse=(e,t)=>{const{id:s}=t;S(t)?this.events.emit(p("pairing_ping",s),{}):f(t)&&this.events.emit(p("pairing_ping",s),{error:t.error})},this.onSessionDeleteRequest=async(e,t)=>{const{id:s}=t;try{this.isValidDisconnect({topic:e,reason:t.params}),await this.sendResult(s,e,!0),await this.deleteSession(e),this.client.events.emit("session_delete",{id:s,topic:e})}catch(r){await this.sendError(s,e,r),this.client.logger.error(r)}},this.onPairingDeleteRequest=async(e,t)=>{const{id:s}=t;try{this.isValidDisconnect({topic:e,reason:t.params}),await this.sendResult(s,e,!0),await this.deletePairing(e),this.client.events.emit("pairing_delete",{id:s,topic:e})}catch(r){await this.sendError(s,e,r),this.client.logger.error(r)}},this.onSessionRequest=async(e,t)=>{const{id:s,params:r}=t;try{this.isValidRequest(R({topic:e},r)),this.client.events.emit("session_request",{id:s,topic:e,params:r})}catch(n){await this.sendError(s,e,n),this.client.logger.error(n)}},this.onSessionRequestResponse=(e,t)=>{const{id:s}=t;S(t)?this.events.emit(p("session_request",s),{result:t.result}):f(t)&&this.events.emit(p("session_request",s),{error:t.error})},this.onSessionEventRequest=async(e,t)=>{const{id:s,params:r}=t;try{this.isValidEmit(R({topic:e},r)),this.client.events.emit("session_event",{id:s,topic:e,params:r})}catch(n){await this.sendError(s,e,n),this.client.logger.error(n)}},this.isValidConnect=async e=>{if(!u(e)){const{message:a}=c("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(e)}`);throw new Error(a)}const{pairingTopic:t,requiredNamespaces:s,relays:r}=e;Se(t)||await this.isValidPairingTopic(t);const n=Re(s,"connect()");if(n)throw new Error(n.message);if(!Ne(r,!0)){const{message:a}=c("MISSING_OR_INVALID",`connect() relays: ${r}`);throw new Error(a)}},this.isValidPair=e=>{if(!u(e)){const{message:t}=c("MISSING_OR_INVALID",`pair() params: ${e}`);throw new Error(t)}if(!xe(e.uri)){const{message:t}=c("MISSING_OR_INVALID",`pair() uri: ${e.uri}`);throw new Error(t)}},this.isValidApprove=async e=>{if(!u(e))throw new Error(c("MISSING_OR_INVALID",`approve() params: ${e}`).message);const{id:t,namespaces:s,relayProtocol:r}=e;await this.isValidProposalId(t);const n=this.client.proposal.get(t),a=J(s,"approve()");if(a)throw new Error(a.message);const h=Z(n.requiredNamespaces,s,"update()");if(h)throw new Error(h.message);if(!b(r,!0)){const{message:l}=c("MISSING_OR_INVALID",`approve() relayProtocol: ${r}`);throw new Error(l)}},this.isValidReject=async e=>{if(!u(e)){const{message:r}=c("MISSING_OR_INVALID",`reject() params: ${e}`);throw new Error(r)}const{id:t,reason:s}=e;if(await this.isValidProposalId(t),!Pe(s)){const{message:r}=c("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(s)}`);throw new Error(r)}},this.isValidSessionSettleRequest=e=>{if(!u(e)){const{message:l}=c("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${e}`);throw new Error(l)}const{relay:t,controller:s,namespaces:r,expiry:n}=e;if(!Te(t)){const{message:l}=c("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=Oe(s,"onSessionSettleRequest()");if(a)throw new Error(a.message);const h=J(r,"onSessionSettleRequest()");if(h)throw new Error(h.message);if(x(n)){const{message:l}=c("EXPIRED","onSessionSettleRequest()");throw new Error(l)}},this.isValidUpdate=async e=>{if(!u(e)){const{message:h}=c("MISSING_OR_INVALID",`update() params: ${e}`);throw new Error(h)}const{topic:t,namespaces:s}=e;await this.isValidSessionTopic(t);const r=this.client.session.get(t),n=J(s,"update()");if(n)throw new Error(n.message);const a=Z(r.requiredNamespaces,s,"update()");if(a)throw new Error(a.message)},this.isValidExtend=async e=>{if(!u(e)){const{message:s}=c("MISSING_OR_INVALID",`extend() params: ${e}`);throw new Error(s)}const{topic:t}=e;await this.isValidSessionTopic(t)},this.isValidRequest=async e=>{if(!u(e)){const{message:a}=c("MISSING_OR_INVALID",`request() params: ${e}`);throw new Error(a)}const{topic:t,request:s,chainId:r}=e;await this.isValidSessionTopic(t);const{namespaces:n}=this.client.session.get(t);if(!B(n,r)){const{message:a}=c("MISSING_OR_INVALID",`request() chainId: ${r}`);throw new Error(a)}if(!Ve(s)){const{message:a}=c("MISSING_OR_INVALID",`request() ${JSON.stringify(s)}`);throw new Error(a)}if(!qe(n,r,s.method)){const{message:a}=c("MISSING_OR_INVALID",`request() method: ${s.method}`);throw new Error(a)}},this.isValidRespond=async e=>{if(!u(e)){const{message:r}=c("MISSING_OR_INVALID",`respond() params: ${e}`);throw new Error(r)}const{topic:t,response:s}=e;if(await this.isValidSessionTopic(t),!Le(s)){const{message:r}=c("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(r)}},this.isValidPing=async e=>{if(!u(e)){const{message:s}=c("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(s)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)},this.isValidEmit=async e=>{if(!u(e)){const{message:a}=c("MISSING_OR_INVALID",`emit() params: ${e}`);throw new Error(a)}const{topic:t,event:s,chainId:r}=e;await this.isValidSessionTopic(t);const{namespaces:n}=this.client.session.get(t);if(!B(n,r)){const{message:a}=c("MISSING_OR_INVALID",`emit() chainId: ${r}`);throw new Error(a)}if(!De(s)){const{message:a}=c("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}if(!be(n,r,s.name)){const{message:a}=c("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}},this.isValidDisconnect=async e=>{if(!u(e)){const{message:s}=c("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(s)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)}}async createPairing(){const i=Ae(),e=await this.client.core.crypto.setSymKey(i),t=P(A),s={protocol:W},r={topic:e,expiry:t,relay:s,active:!1},n=Ce({protocol:this.client.protocol,version:this.client.version,topic:e,symKey:i,relay:s});return await this.client.pairing.set(e,r),await this.client.core.relayer.subscribe(e),await this.setExpiry(e,t),{topic:e,uri:n}}isInitialized(){if(!this.initialized){const{message:i}=c("NOT_INITIALIZED",this.name);throw new Error(i)}}registerRelayerEvents(){this.client.core.relayer.on(ue.message,async i=>{const{topic:e,message:t}=i,s=await this.client.core.crypto.decode(e,t);He(s)?(this.client.history.set(e,s),this.onRelayEventRequest({topic:e,payload:s})):Fe(s)&&(await this.client.history.resolve(s),this.onRelayEventResponse({topic:e,payload:s}))})}registerExpirerEvents(){this.client.expirer.on(m.expired,async i=>{const{topic:e,id:t}=$e(i.target);e?this.client.session.keys.includes(e)?(await this.deleteSession(e),this.client.events.emit("session_expire",{topic:e})):this.client.pairing.keys.includes(e)&&(await this.deletePairing(e),this.client.events.emit("pairing_expire",{topic:e})):t&&await this.deleteProposal(t)})}async isValidPairingTopic(i){if(!b(i,!1)){const{message:e}=c("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(e)}if(!this.client.pairing.keys.includes(i)){const{message:e}=c("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(e)}if(x(this.client.pairing.get(i).expiry)){await this.deletePairing(i);const{message:e}=c("EXPIRED",`pairing topic: ${i}`);throw new Error(e)}}async isValidSessionTopic(i){if(!b(i,!1)){const{message:e}=c("MISSING_OR_INVALID",`session topic should be a string: ${i}`);throw new Error(e)}if(!this.client.session.keys.includes(i)){const{message:e}=c("NO_MATCHING_KEY",`session topic doesn't exist: ${i}`);throw new Error(e)}if(x(this.client.session.get(i).expiry)){await this.deleteSession(i);const{message:e}=c("EXPIRED",`session topic: ${i}`);throw new Error(e)}}async isValidSessionOrPairingTopic(i){if(this.client.session.keys.includes(i))await this.isValidSessionTopic(i);else if(this.client.pairing.keys.includes(i))await this.isValidPairingTopic(i);else if(b(i,!1)){const{message:e}=c("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${i}`);throw new Error(e)}else{const{message:e}=c("MISSING_OR_INVALID",`session or pairing topic should be a string: ${i}`);throw new Error(e)}}async isValidProposalId(i){if(!Ge(i)){const{message:e}=c("MISSING_OR_INVALID",`proposal id should be a number: ${i}`);throw new Error(e)}if(!this.client.proposal.keys.includes(i)){const{message:e}=c("NO_MATCHING_KEY",`proposal id doesn't exist: ${i}`);throw new Error(e)}if(x(this.client.proposal.get(i).expiry)){await this.deleteProposal(i);const{message:e}=c("EXPIRED",`proposal id: ${i}`);throw new Error(e)}}}class ct extends Ee{constructor(i,e){super(i,e),this.core=i,this.logger=e,this.expirations=new Map,this.events=new C.EventEmitter,this.name=se,this.version=ie,this.cached=[],this.initialized=!1,this.storagePrefix=T,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(t=>this.expirations.set(t.target,t)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=t=>{try{const s=this.formatTarget(t);return typeof this.getExpiration(s)<"u"}catch{return!1}},this.set=(t,s)=>{this.isInitialized();const r=this.formatTarget(t),n={target:r,expiry:s};this.expirations.set(r,n),this.checkExpiry(r,n),this.events.emit(m.created,{target:r,expiration:n})},this.get=t=>{this.isInitialized();const s=this.formatTarget(t);return this.getExpiration(s)},this.del=t=>{this.isInitialized();const s=this.formatTarget(t);if(this.has(s)){const r=this.getExpiration(s);this.expirations.delete(s),this.events.emit(m.deleted,{target:s,expiration:r})}},this.on=(t,s)=>{this.events.on(t,s)},this.once=(t,s)=>{this.events.once(t,s)},this.off=(t,s)=>{this.events.off(t,s)},this.removeListener=(t,s)=>{this.events.removeListener(t,s)},this.logger=k(e,this.name)}get context(){return j(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(i){if(typeof i=="string")return ze(i);if(typeof i=="number")return Me(i);const{message:e}=c("UNKNOWN_TYPE",`Target type: ${typeof i}`);throw new Error(e)}async setExpirations(i){await this.core.storage.setItem(this.storageKey,i)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(m.sync)}async restore(){try{const i=await this.getExpirations();if(typeof i>"u"||!i.length)return;if(this.expirations.size){const{message:e}=c("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}this.cached=i,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(i){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(i)}}getExpiration(i){const e=this.expirations.get(i);if(!e){const{message:t}=c("NO_MATCHING_KEY",`${this.name}: ${i}`);throw this.logger.error(t),new Error(t)}return e}checkExpiry(i,e){const{expiry:t}=e;Je(t)-Date.now()<=0&&this.expire(i,e)}expire(i,e){this.expirations.delete(i),this.events.emit(m.expired,{target:i,expiration:e})}checkExpirations(){this.expirations.forEach((i,e)=>this.checkExpiry(e,i))}registerEventListeners(){this.core.heartbeat.on(We.pulse,()=>this.checkExpirations()),this.events.on(m.created,i=>{const e=m.created;this.logger.info(`Emitting ${e}`),this.logger.debug({type:"event",event:e,data:i}),this.persist()}),this.events.on(m.expired,i=>{const e=m.expired;this.logger.info(`Emitting ${e}`),this.logger.debug({type:"event",event:e,data:i}),this.persist()}),this.events.on(m.deleted,i=>{const e=m.deleted;this.logger.info(`Emitting ${e}`),this.logger.debug({type:"event",event:e,data:i}),this.persist()})}isInitialized(){if(!this.initialized){const{message:i}=c("NOT_INITIALIZED",this.name);throw new Error(i)}}}class ht extends _e{constructor(i,e){super(i,e),this.core=i,this.logger=e,this.records=new Map,this.events=new C.EventEmitter,this.name=re,this.version=ne,this.cached=[],this.initialized=!1,this.storagePrefix=T,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(t=>this.records.set(t.id,t)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(t,s,r)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:t,request:s,chainId:r}),this.records.has(s.id))return;const n={id:s.id,topic:t,request:{method:s.method,params:s.params||null},chainId:r};this.records.set(n.id,n),this.events.emit(E.created,n)},this.resolve=async t=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:t}),!this.records.has(t.id))return;const s=await this.getRecord(t.id);typeof s.response>"u"&&(s.response=f(t)?{error:t.error}:{result:t.result},this.records.set(s.id,s),this.events.emit(E.updated,s))},this.get=async(t,s)=>{this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:t,id:s});const r=await this.getRecord(s);if(r.topic!==t){const{message:n}=c("MISMATCHED_TOPIC",`${this.name}, ${s}`);throw this.logger.error(n),new Error(n)}return r},this.delete=(t,s)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:s}),this.values.forEach(r=>{if(r.topic===t){if(typeof s<"u"&&r.id!==s)return;this.records.delete(r.id),this.events.emit(E.deleted,r)}})},this.exists=async(t,s)=>(this.isInitialized(),this.records.has(s)?(await this.getRecord(s)).topic===t:!1),this.on=(t,s)=>{this.events.on(t,s)},this.once=(t,s)=>{this.events.once(t,s)},this.off=(t,s)=>{this.events.off(t,s)},this.removeListener=(t,s)=>{this.events.removeListener(t,s)},this.logger=k(e,this.name)}get context(){return j(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const i=[];return this.values.forEach(e=>{if(typeof e.response<"u")return;const t={topic:e.topic,request:ee(e.request.method,e.request.params,e.id),chainId:e.chainId};return i.push(t)}),i}async setJsonRpcRecords(i){await this.core.storage.setItem(this.storageKey,i)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(i){this.isInitialized();const e=this.records.get(i);if(!e){const{message:t}=c("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(t)}return e}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(E.sync)}async restore(){try{const i=await this.getJsonRpcRecords();if(typeof i>"u"||!i.length)return;if(this.records.size){const{message:e}=c("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}this.cached=i,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}}registerEventListeners(){this.events.on(E.created,i=>{const e=E.created;this.logger.info(`Emitting ${e}`),this.logger.debug({type:"event",event:e,record:i}),this.persist()}),this.events.on(E.updated,i=>{const e=E.updated;this.logger.info(`Emitting ${e}`),this.logger.debug({type:"event",event:e,record:i}),this.persist()}),this.events.on(E.deleted,i=>{const e=E.deleted;this.logger.info(`Emitting ${e}`),this.logger.debug({type:"event",event:e,record:i}),this.persist()})}isInitialized(){if(!this.initialized){const{message:i}=c("NOT_INITIALIZED",this.name);throw new Error(i)}}}class lt extends U{constructor(i,e){super(i,e,oe,T),this.core=i,this.logger=e}}class pt extends U{constructor(i,e){super(i,e,ae,T),this.core=i,this.logger=e}}class dt extends U{constructor(i,e){super(i,e,ce,T),this.core=i,this.logger=e}}class z extends fe{constructor(i){super(i),this.protocol=Y,this.version=X,this.name=$.name,this.events=new C.EventEmitter,this.on=(t,s)=>this.events.on(t,s),this.once=(t,s)=>this.events.once(t,s),this.off=(t,s)=>this.events.off(t,s),this.removeListener=(t,s)=>this.events.removeListener(t,s),this.connect=async t=>{try{return await this.engine.connect(t)}catch(s){throw this.logger.error(s.message),s}},this.pair=async t=>{try{return await this.engine.pair(t)}catch(s){throw this.logger.error(s.message),s}},this.approve=async t=>{try{return await this.engine.approve(t)}catch(s){throw this.logger.error(s.message),s}},this.reject=async t=>{try{return await this.engine.reject(t)}catch(s){throw this.logger.error(s.message),s}},this.update=async t=>{try{return await this.engine.update(t)}catch(s){throw this.logger.error(s.message),s}},this.extend=async t=>{try{return await this.engine.extend(t)}catch(s){throw this.logger.error(s.message),s}},this.request=async t=>{try{return await this.engine.request(t)}catch(s){throw this.logger.error(s.message),s}},this.respond=async t=>{try{return await this.engine.respond(t)}catch(s){throw this.logger.error(s.message),s}},this.ping=async t=>{try{return await this.engine.ping(t)}catch(s){throw this.logger.error(s.message),s}},this.emit=async t=>{try{return await this.engine.emit(t)}catch(s){throw this.logger.error(s.message),s}},this.disconnect=async t=>{try{return await this.engine.disconnect(t)}catch(s){throw this.logger.error(s.message),s}},this.find=t=>{try{return this.engine.find(t)}catch(s){throw this.logger.error(s.message),s}},this.name=i?.name||$.name,this.metadata=i?.metadata||Ke();const e=typeof i?.logger<"u"&&typeof i?.logger!="string"?i.logger:Ue(we({level:i?.logger||$.logger}));this.core=i?.core||new me(i),this.logger=k(e,this.name),this.pairing=new lt(this.core,this.logger),this.session=new dt(this.core,this.logger),this.proposal=new pt(this.core,this.logger),this.history=new ht(this.core,this.logger),this.expirer=new ct(this.core,this.logger),this.engine=new at(this)}static async init(i){const e=new z(i);return await e.initialize(),e}get context(){return j(this.logger)}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.pairing.init(),await this.session.init(),await this.proposal.init(),await this.history.init(),await this.expirer.init(),await this.engine.init(),this.logger.info("SignClient Initilization Success")}catch(i){throw this.logger.info("SignClient Initilization Failure"),this.logger.error(i.message),i}}}const gt=z;export{le as ENGINE_CONTEXT,G as ENGINE_RPC_OPTS,se as EXPIRER_CONTEXT,et as EXPIRER_DEFAULT_TTL,m as EXPIRER_EVENTS,ie as EXPIRER_STORAGE_VERSION,re as HISTORY_CONTEXT,E as HISTORY_EVENTS,ne as HISTORY_STORAGE_VERSION,oe as PAIRING_CONTEXT,tt as PAIRING_DEFAULT_TTL,ae as PROPOSAL_CONTEXT,F as PROPOSAL_EXPIRY,ce as SESSION_CONTEXT,he as SESSION_DEFAULT_TTL,L as SESSION_EXPIRY,H as SIGN_CLIENT_CONTEXT,$ as SIGN_CLIENT_DEFAULT,Be as SIGN_CLIENT_EVENTS,Y as SIGN_CLIENT_PROTOCOL,Qe as SIGN_CLIENT_STORAGE_OPTIONS,T as SIGN_CLIENT_STORAGE_PREFIX,X as SIGN_CLIENT_VERSION,gt as SignClient,z as default};
import{RELAYER_DEFAULT_PROTOCOL as W,RELAYER_EVENTS as ue,Store as U,Core as me}from"@walletconnect/core";import{generateChildLogger as k,getLoggerContext as j,getDefaultLoggerOptions as we}from"@walletconnect/logger";import{IEngine as ye,IExpirer as _e,IJsonRpcHistory as Ee,ISignClient as fe}from"@walletconnect/types";import{calcExpiry as P,createDelayedPromise as N,engineEvent as p,getInternalError as c,parseUri as Ie,getSdkError as E,isSessionCompatible as ve,isExpired as x,isValidParams as u,isUndefined as Se,isValidRequiredNamespaces as Re,isValidRelays as Ne,isValidUrl as xe,isValidNamespaces as J,isConformingNamespaces as Z,isValidString as b,isValidErrorReason as Pe,isValidRelay as Te,isValidController as Oe,isValidNamespacesChainId as B,isValidRequest as Ve,isValidNamespacesRequest as qe,isValidResponse as Le,isValidEvent as De,isValidNamespacesEvent as be,generateRandomBytes32 as Ae,formatUri as Ce,parseExpirerTarget as $e,isValidId as Ge,formatTopicTarget as ze,formatIdTarget as Me,getAppMetadata as Ke}from"@walletconnect/utils";import Ue from"pino";import{ONE_DAY as ke,THIRTY_DAYS as Q,SEVEN_DAYS as je,FIVE_MINUTES as A,toMiliseconds as Je}from"@walletconnect/time";import{isJsonRpcResult as S,isJsonRpcError as f,formatJsonRpcRequest as ee,formatJsonRpcResult as Ye,formatJsonRpcError as Xe,isJsonRpcRequest as He,isJsonRpcResponse as Fe}from"@walletconnect/jsonrpc-utils";import{HEARTBEAT_EVENTS as We}from"@walletconnect/heartbeat";function d(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}var C=d;d.EventEmitter=d,d.prototype._events=void 0,d.prototype._maxListeners=void 0,d.defaultMaxListeners=10,d.prototype.setMaxListeners=function(o){if(!Ze(o)||o<0||isNaN(o))throw TypeError("n must be a positive number");return this._maxListeners=o,this},d.prototype.emit=function(o){var i,e,t,s,r,n;if(this._events||(this._events={}),o==="error"&&(!this._events.error||q(this._events.error)&&!this._events.error.length)){if(i=arguments[1],i instanceof Error)throw i;var a=new Error('Uncaught, unspecified "error" event. ('+i+")");throw a.context=i,a}if(e=this._events[o],te(e))return!1;if(I(e))switch(arguments.length){case 1:e.call(this);break;case 2:e.call(this,arguments[1]);break;case 3:e.call(this,arguments[1],arguments[2]);break;default:s=Array.prototype.slice.call(arguments,1),e.apply(this,s)}else if(q(e))for(s=Array.prototype.slice.call(arguments,1),n=e.slice(),t=n.length,r=0;r<t;r++)n[r].apply(this,s);return!0},d.prototype.addListener=function(o,i){var e;if(!I(i))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",o,I(i.listener)?i.listener:i),this._events[o]?q(this._events[o])?this._events[o].push(i):this._events[o]=[this._events[o],i]:this._events[o]=i,q(this._events[o])&&!this._events[o].warned&&(te(this._maxListeners)?e=d.defaultMaxListeners:e=this._maxListeners,e&&e>0&&this._events[o].length>e&&(this._events[o].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[o].length),typeof console.trace=="function"&&console.trace())),this},d.prototype.on=d.prototype.addListener,d.prototype.once=function(o,i){if(!I(i))throw TypeError("listener must be a function");var e=!1;function t(){this.removeListener(o,t),e||(e=!0,i.apply(this,arguments))}return t.listener=i,this.on(o,t),this},d.prototype.removeListener=function(o,i){var e,t,s,r;if(!I(i))throw TypeError("listener must be a function");if(!this._events||!this._events[o])return this;if(e=this._events[o],s=e.length,t=-1,e===i||I(e.listener)&&e.listener===i)delete this._events[o],this._events.removeListener&&this.emit("removeListener",o,i);else if(q(e)){for(r=s;r-- >0;)if(e[r]===i||e[r].listener&&e[r].listener===i){t=r;break}if(t<0)return this;e.length===1?(e.length=0,delete this._events[o]):e.splice(t,1),this._events.removeListener&&this.emit("removeListener",o,i)}return this},d.prototype.removeAllListeners=function(o){var i,e;if(!this._events)return this;if(!this._events.removeListener)return arguments.length===0?this._events={}:this._events[o]&&delete this._events[o],this;if(arguments.length===0){for(i in this._events)i!=="removeListener"&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events={},this}if(e=this._events[o],I(e))this.removeListener(o,e);else if(e)for(;e.length;)this.removeListener(o,e[e.length-1]);return delete this._events[o],this},d.prototype.listeners=function(o){var i;return!this._events||!this._events[o]?i=[]:I(this._events[o])?i=[this._events[o]]:i=this._events[o].slice(),i},d.prototype.listenerCount=function(o){if(this._events){var i=this._events[o];if(I(i))return 1;if(i)return i.length}return 0},d.listenerCount=function(o,i){return o.listenerCount(i)};function I(o){return typeof o=="function"}function Ze(o){return typeof o=="number"}function q(o){return typeof o=="object"&&o!==null}function te(o){return o===void 0}const Y="wc",X=2,H="client",T=`${Y}@${X}:${H}:`,$={name:H,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},Be={session_proposal:"session_proposal",session_update:"session_update",session_extend:"session_extend",session_ping:"session_ping",pairing_ping:"pairing_ping",session_delete:"session_delete",session_expire:"session_expire",pairing_delete:"pairing_delete",pairing_expire:"pairing_expire",session_request:"session_request",session_event:"session_event",proposal_expire:"proposal_expire"},Qe={database:":memory:"},se="expirer",m={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},ie="0.3",et=ke,_={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},re="history",ne="0.3",oe="pairing",tt=Q,ae="proposal",F=P(Q),ce="session",he=je,L=P(he),le="engine",G={wc_pairingDelete:{req:{prompt:!1,tag:1e3},res:{prompt:!1,tag:1001}},wc_pairingPing:{req:{prompt:!1,tag:1002},res:{prompt:!1,tag:1003}},wc_sessionPropose:{req:{prompt:!0,tag:1100},res:{prompt:!1,tag:1101}},wc_sessionSettle:{req:{prompt:!1,tag:1102},res:{prompt:!1,tag:1103}},wc_sessionUpdate:{req:{prompt:!1,tag:1104},res:{prompt:!1,tag:1105}},wc_sessionExtend:{req:{prompt:!1,tag:1106},res:{prompt:!1,tag:1107}},wc_sessionRequest:{req:{prompt:!0,tag:1108},res:{prompt:!1,tag:1109}},wc_sessionEvent:{req:{prompt:!0,tag:1110},res:{prompt:!1,tag:1111}},wc_sessionDelete:{req:{prompt:!1,tag:1112},res:{prompt:!1,tag:1113}},wc_sessionPing:{req:{prompt:!1,tag:1114},res:{prompt:!1,tag:1115}}};var st=Object.defineProperty,it=Object.defineProperties,rt=Object.getOwnPropertyDescriptors,pe=Object.getOwnPropertySymbols,nt=Object.prototype.hasOwnProperty,ot=Object.prototype.propertyIsEnumerable,de=(o,i,e)=>i in o?st(o,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[i]=e,R=(o,i)=>{for(var e in i||(i={}))nt.call(i,e)&&de(o,e,i[e]);if(pe)for(var e of pe(i))ot.call(i,e)&&de(o,e,i[e]);return o},ge=(o,i)=>it(o,rt(i));class at extends ye{constructor(i){super(i),this.events=new C,this.initialized=!1,this.name=le,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0)},this.connect=async e=>{this.isInitialized(),await this.isValidConnect(e);const{pairingTopic:t,requiredNamespaces:s,relays:r}=e;let n=t,a,h=!1;if(n&&(h=this.client.pairing.get(n).active),!n||!h){const{topic:v,uri:g}=await this.createPairing();n=v,a=g}const l=await this.client.core.crypto.generateKeyPair(),w={requiredNamespaces:s,relays:r??[{protocol:W}],proposer:{publicKey:l,metadata:this.client.metadata}},{reject:y,resolve:O,done:M}=N();if(this.events.once(p("session_connect"),async({error:v,session:g})=>{if(v)y(v);else if(g){g.self.publicKey=l;const V=ge(R({},g),{requiredNamespaces:s});await this.client.session.set(g.topic,V),await this.setExpiry(g.topic,g.expiry),n&&await this.client.pairing.update(n,{peerMetadata:g.peer.metadata}),O(V)}}),!n){const{message:v}=c("NO_MATCHING_KEY",`connect() pairing topic: ${n}`);throw new Error(v)}const D=await this.sendRequest(n,"wc_sessionPropose",w),K=P(A);return await this.setProposal(D,R({id:D,expiry:K},w)),{uri:a,approval:M}},this.pair=async e=>{this.isInitialized(),this.isValidPair(e);const{topic:t,symKey:s,relay:r}=Ie(e.uri),n=P(A),a={topic:t,relay:r,expiry:n,active:!1};return await this.client.pairing.set(t,a),await this.client.core.crypto.setSymKey(s,t),await this.client.core.relayer.subscribe(t,{relay:r}),await this.setExpiry(t,n),a},this.approve=async e=>{this.isInitialized(),await this.isValidApprove(e);const{id:t,relayProtocol:s,namespaces:r}=e,{pairingTopic:n,proposer:a,requiredNamespaces:h}=this.client.proposal.get(t),l=await this.client.core.crypto.generateKeyPair(),w=a.publicKey,y=await this.client.core.crypto.generateSharedKey(l,w),O={relay:{protocol:s??"irn"},namespaces:r,requiredNamespaces:h,controller:{publicKey:l,metadata:this.client.metadata},expiry:L};await this.client.core.relayer.subscribe(y);const M=await this.sendRequest(y,"wc_sessionSettle",O),{done:D,resolve:K,reject:v}=N();this.events.once(p("session_approve",M),({error:V})=>{V?v(V):K(this.client.session.get(y))});const g=ge(R({},O),{topic:y,acknowledged:!1,self:O.controller,peer:{publicKey:a.publicKey,metadata:a.metadata},controller:l});return await this.client.session.set(y,g),await this.setExpiry(y,L),n&&await this.client.pairing.update(n,{peerMetadata:g.peer.metadata}),n&&t&&(await this.sendResult(t,n,{relay:{protocol:s??"irn"},responderPublicKey:l}),await this.client.proposal.delete(t,E("USER_DISCONNECTED")),await this.activatePairing(n)),{topic:y,acknowledged:D}},this.reject=async e=>{this.isInitialized(),await this.isValidReject(e);const{id:t,reason:s}=e,{pairingTopic:r}=this.client.proposal.get(t);r&&(await this.sendError(t,r,s),await this.client.proposal.delete(t,E("USER_DISCONNECTED")))},this.update=async e=>{this.isInitialized(),await this.isValidUpdate(e);const{topic:t,namespaces:s}=e,r=await this.sendRequest(t,"wc_sessionUpdate",{namespaces:s}),{done:n,resolve:a,reject:h}=N();return this.events.once(p("session_update",r),({error:l})=>{l?h(l):a()}),await this.client.session.update(t,{namespaces:s}),{acknowledged:n}},this.extend=async e=>{this.isInitialized(),await this.isValidExtend(e);const{topic:t}=e,s=await this.sendRequest(t,"wc_sessionExtend",{}),{done:r,resolve:n,reject:a}=N();return this.events.once(p("session_extend",s),({error:h})=>{h?a(h):n()}),await this.setExpiry(t,L),{acknowledged:r}},this.request=async e=>{this.isInitialized(),await this.isValidRequest(e);const{chainId:t,request:s,topic:r}=e,n=await this.sendRequest(r,"wc_sessionRequest",{request:s,chainId:t}),{done:a,resolve:h,reject:l}=N();return this.events.once(p("session_request",n),({error:w,result:y})=>{w?l(w):h(y)}),await a()},this.respond=async e=>{this.isInitialized(),await this.isValidRespond(e);const{topic:t,response:s}=e,{id:r}=s;S(s)?await this.sendResult(r,t,s.result):f(s)&&await this.sendError(r,t,s.error)},this.ping=async e=>{this.isInitialized(),await this.isValidPing(e);const{topic:t}=e;if(this.client.session.keys.includes(t)){const s=await this.sendRequest(t,"wc_sessionPing",{}),{done:r,resolve:n,reject:a}=N();this.events.once(p("session_ping",s),({error:h})=>{h?a(h):n()}),await r()}else if(this.client.pairing.keys.includes(t)){const s=await this.sendRequest(t,"wc_pairingPing",{}),{done:r,resolve:n,reject:a}=N();this.events.once(p("pairing_ping",s),({error:h})=>{h?a(h):n()}),await r()}},this.emit=async e=>{this.isInitialized(),await this.isValidEmit(e);const{topic:t,event:s,chainId:r}=e;await this.sendRequest(t,"wc_sessionEvent",{event:s,chainId:r})},this.disconnect=async e=>{this.isInitialized(),await this.isValidDisconnect(e);const{topic:t}=e;this.client.session.keys.includes(t)?(await this.sendRequest(t,"wc_sessionDelete",E("USER_DISCONNECTED")),await this.deleteSession(t)):this.client.pairing.keys.includes(t)&&(await this.sendRequest(t,"wc_pairingDelete",E("USER_DISCONNECTED")),await this.deletePairing(t))},this.find=e=>(this.isInitialized(),this.client.session.getAll().filter(t=>ve(t,e))),this.activatePairing=async e=>{await this.client.pairing.update(e,{active:!0,expiry:F}),await this.setExpiry(e,F)},this.deleteSession=async e=>{const{self:t}=this.client.session.get(e);await Promise.all([this.client.core.relayer.unsubscribe(e),this.client.session.delete(e,E("USER_DISCONNECTED")),this.client.core.crypto.deleteKeyPair(t.publicKey),this.client.core.crypto.deleteSymKey(e),this.client.expirer.del(e)])},this.deletePairing=async e=>{await Promise.all([this.client.core.relayer.unsubscribe(e),this.client.pairing.delete(e,E("USER_DISCONNECTED")),this.client.core.crypto.deleteSymKey(e),this.client.expirer.del(e)])},this.deleteProposal=async e=>{await Promise.all([this.client.proposal.delete(e,E("USER_DISCONNECTED")),this.client.expirer.del(e)])},this.setExpiry=async(e,t)=>{this.client.pairing.keys.includes(e)?await this.client.pairing.update(e,{expiry:t}):this.client.session.keys.includes(e)&&await this.client.session.update(e,{expiry:t}),this.client.expirer.set(e,t)},this.setProposal=async(e,t)=>{await this.client.proposal.set(e,t),this.client.expirer.set(e,t.expiry)},this.sendRequest=async(e,t,s)=>{const r=ee(t,s),n=await this.client.core.crypto.encode(e,r),a=G[t].req;return await this.client.core.relayer.publish(e,n,a),this.client.history.set(e,r),r.id},this.sendResult=async(e,t,s)=>{const r=Ye(e,s),n=await this.client.core.crypto.encode(t,r),a=await this.client.history.get(t,e),h=G[a.request.method].res;await this.client.core.relayer.publish(t,n,h),await this.client.history.resolve(r)},this.sendError=async(e,t,s)=>{const r=Xe(e,s),n=await this.client.core.crypto.encode(t,r),a=await this.client.history.get(t,e),h=G[a.request.method].res;await this.client.core.relayer.publish(t,n,h),await this.client.history.resolve(r)},this.cleanup=async()=>{const e=[],t=[],s=[];this.client.session.getAll().forEach(r=>{x(r.expiry)&&e.push(r.topic)}),this.client.pairing.getAll().forEach(r=>{x(r.expiry)&&t.push(r.topic)}),this.client.proposal.getAll().forEach(r=>{x(r.expiry)&&s.push(r.id)}),await Promise.all([...e.map(this.deleteSession),...t.map(this.deletePairing),...s.map(this.deleteProposal)])},this.onRelayEventRequest=e=>{const{topic:t,payload:s}=e,r=s.method;switch(r){case"wc_sessionPropose":return this.onSessionProposeRequest(t,s);case"wc_sessionSettle":return this.onSessionSettleRequest(t,s);case"wc_sessionUpdate":return this.onSessionUpdateRequest(t,s);case"wc_sessionExtend":return this.onSessionExtendRequest(t,s);case"wc_sessionPing":return this.onSessionPingRequest(t,s);case"wc_pairingPing":return this.onPairingPingRequest(t,s);case"wc_sessionDelete":return this.onSessionDeleteRequest(t,s);case"wc_pairingDelete":return this.onPairingDeleteRequest(t,s);case"wc_sessionRequest":return this.onSessionRequest(t,s);case"wc_sessionEvent":return this.onSessionEventRequest(t,s);default:return this.client.logger.info(`Unsupported request method ${r}`)}},this.onRelayEventResponse=async e=>{const{topic:t,payload:s}=e,r=(await this.client.history.get(t,s.id)).request.method;switch(r){case"wc_sessionPropose":return this.onSessionProposeResponse(t,s);case"wc_sessionSettle":return this.onSessionSettleResponse(t,s);case"wc_sessionUpdate":return this.onSessionUpdateResponse(t,s);case"wc_sessionExtend":return this.onSessionExtendResponse(t,s);case"wc_sessionPing":return this.onSessionPingResponse(t,s);case"wc_pairingPing":return this.onPairingPingResponse(t,s);case"wc_sessionRequest":return this.onSessionRequestResponse(t,s);default:return this.client.logger.info(`Unsupported response method ${r}`)}},this.onSessionProposeRequest=async(e,t)=>{const{params:s,id:r}=t;try{this.isValidConnect(R({},t.params));const n=P(A),a=R({id:r,pairingTopic:e,expiry:n},s);await this.setProposal(r,a),this.client.events.emit("session_proposal",{id:r,params:a})}catch(n){await this.sendError(r,e,n),this.client.logger.error(n)}},this.onSessionProposeResponse=async(e,t)=>{const{id:s}=t;if(S(t)){const{result:r}=t;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:r});const n=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:n});const a=n.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:a});const h=r.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:h});const l=await this.client.core.crypto.generateSharedKey(a,h);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:l});const w=await this.client.core.relayer.subscribe(l);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:w}),await this.activatePairing(e)}else f(t)&&(await this.client.proposal.delete(s,E("USER_DISCONNECTED")),this.events.emit(p("session_connect"),{error:t.error}))},this.onSessionSettleRequest=async(e,t)=>{const{id:s,params:r}=t;try{this.isValidSessionSettleRequest(r);const{relay:n,controller:a,expiry:h,namespaces:l}=t.params,w={topic:e,relay:n,expiry:h,namespaces:l,acknowledged:!0,controller:a.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}};await this.sendResult(t.id,e,!0),this.events.emit(p("session_connect"),{session:w})}catch(n){await this.sendError(s,e,n),this.client.logger.error(n)}},this.onSessionSettleResponse=async(e,t)=>{const{id:s}=t;S(t)?(await this.client.session.update(e,{acknowledged:!0}),this.events.emit(p("session_approve",s),{})):f(t)&&(await this.client.session.delete(e,E("USER_DISCONNECTED")),this.events.emit(p("session_approve",s),{error:t.error}))},this.onSessionUpdateRequest=async(e,t)=>{const{params:s,id:r}=t;try{this.isValidUpdate(R({topic:e},s)),await this.client.session.update(e,{namespaces:s.namespaces}),await this.sendResult(r,e,!0),this.client.events.emit("session_update",{id:r,topic:e,params:s})}catch(n){await this.sendError(r,e,n),this.client.logger.error(n)}},this.onSessionUpdateResponse=(e,t)=>{const{id:s}=t;S(t)?this.events.emit(p("session_update",s),{}):f(t)&&this.events.emit(p("session_update",s),{error:t.error})},this.onSessionExtendRequest=async(e,t)=>{const{id:s}=t;try{this.isValidExtend({topic:e}),await this.setExpiry(e,L),await this.sendResult(s,e,!0),this.client.events.emit("session_extend",{id:s,topic:e})}catch(r){await this.sendError(s,e,r),this.client.logger.error(r)}},this.onSessionExtendResponse=(e,t)=>{const{id:s}=t;S(t)?this.events.emit(p("session_extend",s),{}):f(t)&&this.events.emit(p("session_extend",s),{error:t.error})},this.onSessionPingRequest=async(e,t)=>{const{id:s}=t;try{this.isValidPing({topic:e}),await this.sendResult(s,e,!0),this.client.events.emit("session_ping",{id:s,topic:e})}catch(r){await this.sendError(s,e,r),this.client.logger.error(r)}},this.onSessionPingResponse=(e,t)=>{const{id:s}=t;S(t)?this.events.emit(p("session_ping",s),{}):f(t)&&this.events.emit(p("session_ping",s),{error:t.error})},this.onPairingPingRequest=async(e,t)=>{const{id:s}=t;try{this.isValidPing({topic:e}),await this.sendResult(s,e,!0),this.client.events.emit("pairing_ping",{id:s,topic:e})}catch(r){await this.sendError(s,e,r),this.client.logger.error(r)}},this.onPairingPingResponse=(e,t)=>{const{id:s}=t;S(t)?this.events.emit(p("pairing_ping",s),{}):f(t)&&this.events.emit(p("pairing_ping",s),{error:t.error})},this.onSessionDeleteRequest=async(e,t)=>{const{id:s}=t;try{this.isValidDisconnect({topic:e,reason:t.params}),await this.sendResult(s,e,!0),await this.deleteSession(e),this.client.events.emit("session_delete",{id:s,topic:e})}catch(r){await this.sendError(s,e,r),this.client.logger.error(r)}},this.onPairingDeleteRequest=async(e,t)=>{const{id:s}=t;try{this.isValidDisconnect({topic:e,reason:t.params}),await this.sendResult(s,e,!0),await this.deletePairing(e),this.client.events.emit("pairing_delete",{id:s,topic:e})}catch(r){await this.sendError(s,e,r),this.client.logger.error(r)}},this.onSessionRequest=async(e,t)=>{const{id:s,params:r}=t;try{this.isValidRequest(R({topic:e},r)),this.client.events.emit("session_request",{id:s,topic:e,params:r})}catch(n){await this.sendError(s,e,n),this.client.logger.error(n)}},this.onSessionRequestResponse=(e,t)=>{const{id:s}=t;S(t)?this.events.emit(p("session_request",s),{result:t.result}):f(t)&&this.events.emit(p("session_request",s),{error:t.error})},this.onSessionEventRequest=async(e,t)=>{const{id:s,params:r}=t;try{this.isValidEmit(R({topic:e},r)),this.client.events.emit("session_event",{id:s,topic:e,params:r})}catch(n){await this.sendError(s,e,n),this.client.logger.error(n)}},this.isValidConnect=async e=>{if(!u(e)){const{message:a}=c("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(e)}`);throw new Error(a)}const{pairingTopic:t,requiredNamespaces:s,relays:r}=e;Se(t)||await this.isValidPairingTopic(t);const n=Re(s,"connect()");if(n)throw new Error(n.message);if(!Ne(r,!0)){const{message:a}=c("MISSING_OR_INVALID",`connect() relays: ${r}`);throw new Error(a)}},this.isValidPair=e=>{if(!u(e)){const{message:t}=c("MISSING_OR_INVALID",`pair() params: ${e}`);throw new Error(t)}if(!xe(e.uri)){const{message:t}=c("MISSING_OR_INVALID",`pair() uri: ${e.uri}`);throw new Error(t)}},this.isValidApprove=async e=>{if(!u(e))throw new Error(c("MISSING_OR_INVALID",`approve() params: ${e}`).message);const{id:t,namespaces:s,relayProtocol:r}=e;await this.isValidProposalId(t);const n=this.client.proposal.get(t),a=J(s,"approve()");if(a)throw new Error(a.message);const h=Z(n.requiredNamespaces,s,"update()");if(h)throw new Error(h.message);if(!b(r,!0)){const{message:l}=c("MISSING_OR_INVALID",`approve() relayProtocol: ${r}`);throw new Error(l)}},this.isValidReject=async e=>{if(!u(e)){const{message:r}=c("MISSING_OR_INVALID",`reject() params: ${e}`);throw new Error(r)}const{id:t,reason:s}=e;if(await this.isValidProposalId(t),!Pe(s)){const{message:r}=c("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(s)}`);throw new Error(r)}},this.isValidSessionSettleRequest=e=>{if(!u(e)){const{message:l}=c("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${e}`);throw new Error(l)}const{relay:t,controller:s,namespaces:r,expiry:n}=e;if(!Te(t)){const{message:l}=c("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=Oe(s,"onSessionSettleRequest()");if(a)throw new Error(a.message);const h=J(r,"onSessionSettleRequest()");if(h)throw new Error(h.message);if(x(n)){const{message:l}=c("EXPIRED","onSessionSettleRequest()");throw new Error(l)}},this.isValidUpdate=async e=>{if(!u(e)){const{message:h}=c("MISSING_OR_INVALID",`update() params: ${e}`);throw new Error(h)}const{topic:t,namespaces:s}=e;await this.isValidSessionTopic(t);const r=this.client.session.get(t),n=J(s,"update()");if(n)throw new Error(n.message);const a=Z(r.requiredNamespaces,s,"update()");if(a)throw new Error(a.message)},this.isValidExtend=async e=>{if(!u(e)){const{message:s}=c("MISSING_OR_INVALID",`extend() params: ${e}`);throw new Error(s)}const{topic:t}=e;await this.isValidSessionTopic(t)},this.isValidRequest=async e=>{if(!u(e)){const{message:a}=c("MISSING_OR_INVALID",`request() params: ${e}`);throw new Error(a)}const{topic:t,request:s,chainId:r}=e;await this.isValidSessionTopic(t);const{namespaces:n}=this.client.session.get(t);if(!B(n,r)){const{message:a}=c("MISSING_OR_INVALID",`request() chainId: ${r}`);throw new Error(a)}if(!Ve(s)){const{message:a}=c("MISSING_OR_INVALID",`request() ${JSON.stringify(s)}`);throw new Error(a)}if(!qe(n,r,s.method)){const{message:a}=c("MISSING_OR_INVALID",`request() method: ${s.method}`);throw new Error(a)}},this.isValidRespond=async e=>{if(!u(e)){const{message:r}=c("MISSING_OR_INVALID",`respond() params: ${e}`);throw new Error(r)}const{topic:t,response:s}=e;if(await this.isValidSessionTopic(t),!Le(s)){const{message:r}=c("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(r)}},this.isValidPing=async e=>{if(!u(e)){const{message:s}=c("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(s)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)},this.isValidEmit=async e=>{if(!u(e)){const{message:a}=c("MISSING_OR_INVALID",`emit() params: ${e}`);throw new Error(a)}const{topic:t,event:s,chainId:r}=e;await this.isValidSessionTopic(t);const{namespaces:n}=this.client.session.get(t);if(!B(n,r)){const{message:a}=c("MISSING_OR_INVALID",`emit() chainId: ${r}`);throw new Error(a)}if(!De(s)){const{message:a}=c("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}if(!be(n,r,s.name)){const{message:a}=c("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}},this.isValidDisconnect=async e=>{if(!u(e)){const{message:s}=c("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(s)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)}}async createPairing(){const i=Ae(),e=await this.client.core.crypto.setSymKey(i),t=P(A),s={protocol:W},r={topic:e,expiry:t,relay:s,active:!1},n=Ce({protocol:this.client.protocol,version:this.client.version,topic:e,symKey:i,relay:s});return await this.client.pairing.set(e,r),await this.client.core.relayer.subscribe(e),await this.setExpiry(e,t),{topic:e,uri:n}}isInitialized(){if(!this.initialized){const{message:i}=c("NOT_INITIALIZED",this.name);throw new Error(i)}}registerRelayerEvents(){this.client.core.relayer.on(ue.message,async i=>{const{topic:e,message:t}=i,s=await this.client.core.crypto.decode(e,t);He(s)?(this.client.history.set(e,s),this.onRelayEventRequest({topic:e,payload:s})):Fe(s)&&(await this.client.history.resolve(s),this.onRelayEventResponse({topic:e,payload:s}))})}registerExpirerEvents(){this.client.expirer.on(m.expired,async i=>{const{topic:e,id:t}=$e(i.target);e?this.client.session.keys.includes(e)?(await this.deleteSession(e),this.client.events.emit("session_expire",{topic:e})):this.client.pairing.keys.includes(e)&&(await this.deletePairing(e),this.client.events.emit("pairing_expire",{topic:e})):t&&await this.deleteProposal(t)})}async isValidPairingTopic(i){if(!b(i,!1)){const{message:e}=c("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(e)}if(!this.client.pairing.keys.includes(i)){const{message:e}=c("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(e)}if(x(this.client.pairing.get(i).expiry)){await this.deletePairing(i);const{message:e}=c("EXPIRED",`pairing topic: ${i}`);throw new Error(e)}}async isValidSessionTopic(i){if(!b(i,!1)){const{message:e}=c("MISSING_OR_INVALID",`session topic should be a string: ${i}`);throw new Error(e)}if(!this.client.session.keys.includes(i)){const{message:e}=c("NO_MATCHING_KEY",`session topic doesn't exist: ${i}`);throw new Error(e)}if(x(this.client.session.get(i).expiry)){await this.deleteSession(i);const{message:e}=c("EXPIRED",`session topic: ${i}`);throw new Error(e)}}async isValidSessionOrPairingTopic(i){if(this.client.session.keys.includes(i))await this.isValidSessionTopic(i);else if(this.client.pairing.keys.includes(i))await this.isValidPairingTopic(i);else if(b(i,!1)){const{message:e}=c("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${i}`);throw new Error(e)}else{const{message:e}=c("MISSING_OR_INVALID",`session or pairing topic should be a string: ${i}`);throw new Error(e)}}async isValidProposalId(i){if(!Ge(i)){const{message:e}=c("MISSING_OR_INVALID",`proposal id should be a number: ${i}`);throw new Error(e)}if(!this.client.proposal.keys.includes(i)){const{message:e}=c("NO_MATCHING_KEY",`proposal id doesn't exist: ${i}`);throw new Error(e)}if(x(this.client.proposal.get(i).expiry)){await this.deleteProposal(i);const{message:e}=c("EXPIRED",`proposal id: ${i}`);throw new Error(e)}}}class ct extends _e{constructor(i,e){super(i,e),this.core=i,this.logger=e,this.expirations=new Map,this.events=new C.EventEmitter,this.name=se,this.version=ie,this.cached=[],this.initialized=!1,this.storagePrefix=T,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(t=>this.expirations.set(t.target,t)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=t=>{try{const s=this.formatTarget(t);return typeof this.getExpiration(s)<"u"}catch{return!1}},this.set=(t,s)=>{this.isInitialized();const r=this.formatTarget(t),n={target:r,expiry:s};this.expirations.set(r,n),this.checkExpiry(r,n),this.events.emit(m.created,{target:r,expiration:n})},this.get=t=>{this.isInitialized();const s=this.formatTarget(t);return this.getExpiration(s)},this.del=t=>{this.isInitialized();const s=this.formatTarget(t);if(this.has(s)){const r=this.getExpiration(s);this.expirations.delete(s),this.events.emit(m.deleted,{target:s,expiration:r})}},this.on=(t,s)=>{this.events.on(t,s)},this.once=(t,s)=>{this.events.once(t,s)},this.off=(t,s)=>{this.events.off(t,s)},this.removeListener=(t,s)=>{this.events.removeListener(t,s)},this.logger=k(e,this.name)}get context(){return j(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(i){if(typeof i=="string")return ze(i);if(typeof i=="number")return Me(i);const{message:e}=c("UNKNOWN_TYPE",`Target type: ${typeof i}`);throw new Error(e)}async setExpirations(i){await this.core.storage.setItem(this.storageKey,i)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(m.sync)}async restore(){try{const i=await this.getExpirations();if(typeof i>"u"||!i.length)return;if(this.expirations.size){const{message:e}=c("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}this.cached=i,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(i){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(i)}}getExpiration(i){const e=this.expirations.get(i);if(!e){const{message:t}=c("NO_MATCHING_KEY",`${this.name}: ${i}`);throw this.logger.error(t),new Error(t)}return e}checkExpiry(i,e){const{expiry:t}=e;Je(t)-Date.now()<=0&&this.expire(i,e)}expire(i,e){this.expirations.delete(i),this.events.emit(m.expired,{target:i,expiration:e})}checkExpirations(){this.expirations.forEach((i,e)=>this.checkExpiry(e,i))}registerEventListeners(){this.core.heartbeat.on(We.pulse,()=>this.checkExpirations()),this.events.on(m.created,i=>{const e=m.created;this.logger.info(`Emitting ${e}`),this.logger.debug({type:"event",event:e,data:i}),this.persist()}),this.events.on(m.expired,i=>{const e=m.expired;this.logger.info(`Emitting ${e}`),this.logger.debug({type:"event",event:e,data:i}),this.persist()}),this.events.on(m.deleted,i=>{const e=m.deleted;this.logger.info(`Emitting ${e}`),this.logger.debug({type:"event",event:e,data:i}),this.persist()})}isInitialized(){if(!this.initialized){const{message:i}=c("NOT_INITIALIZED",this.name);throw new Error(i)}}}class ht extends Ee{constructor(i,e){super(i,e),this.core=i,this.logger=e,this.records=new Map,this.events=new C.EventEmitter,this.name=re,this.version=ne,this.cached=[],this.initialized=!1,this.storagePrefix=T,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(t=>this.records.set(t.id,t)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(t,s,r)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:t,request:s,chainId:r}),this.records.has(s.id))return;const n={id:s.id,topic:t,request:{method:s.method,params:s.params||null},chainId:r};this.records.set(n.id,n),this.events.emit(_.created,n)},this.resolve=async t=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:t}),!this.records.has(t.id))return;const s=await this.getRecord(t.id);typeof s.response>"u"&&(s.response=f(t)?{error:t.error}:{result:t.result},this.records.set(s.id,s),this.events.emit(_.updated,s))},this.get=async(t,s)=>{this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:t,id:s});const r=await this.getRecord(s);if(r.topic!==t){const{message:n}=c("MISMATCHED_TOPIC",`${this.name}, ${s}`);throw this.logger.error(n),new Error(n)}return r},this.delete=(t,s)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:s}),this.values.forEach(r=>{if(r.topic===t){if(typeof s<"u"&&r.id!==s)return;this.records.delete(r.id),this.events.emit(_.deleted,r)}})},this.exists=async(t,s)=>(this.isInitialized(),this.records.has(s)?(await this.getRecord(s)).topic===t:!1),this.on=(t,s)=>{this.events.on(t,s)},this.once=(t,s)=>{this.events.once(t,s)},this.off=(t,s)=>{this.events.off(t,s)},this.removeListener=(t,s)=>{this.events.removeListener(t,s)},this.logger=k(e,this.name)}get context(){return j(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const i=[];return this.values.forEach(e=>{if(typeof e.response<"u")return;const t={topic:e.topic,request:ee(e.request.method,e.request.params,e.id),chainId:e.chainId};return i.push(t)}),i}async setJsonRpcRecords(i){await this.core.storage.setItem(this.storageKey,i)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(i){this.isInitialized();const e=this.records.get(i);if(!e){const{message:t}=c("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(t)}return e}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(_.sync)}async restore(){try{const i=await this.getJsonRpcRecords();if(typeof i>"u"||!i.length)return;if(this.records.size){const{message:e}=c("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}this.cached=i,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}}registerEventListeners(){this.events.on(_.created,i=>{const e=_.created;this.logger.info(`Emitting ${e}`),this.logger.debug({type:"event",event:e,record:i}),this.persist()}),this.events.on(_.updated,i=>{const e=_.updated;this.logger.info(`Emitting ${e}`),this.logger.debug({type:"event",event:e,record:i}),this.persist()}),this.events.on(_.deleted,i=>{const e=_.deleted;this.logger.info(`Emitting ${e}`),this.logger.debug({type:"event",event:e,record:i}),this.persist()})}isInitialized(){if(!this.initialized){const{message:i}=c("NOT_INITIALIZED",this.name);throw new Error(i)}}}class lt extends U{constructor(i,e){super(i,e,oe,T),this.core=i,this.logger=e}}class pt extends U{constructor(i,e){super(i,e,ae,T),this.core=i,this.logger=e}}class dt extends U{constructor(i,e){super(i,e,ce,T),this.core=i,this.logger=e}}class z extends fe{constructor(i){super(i),this.protocol=Y,this.version=X,this.name=$.name,this.events=new C.EventEmitter,this.on=(t,s)=>this.events.on(t,s),this.once=(t,s)=>this.events.once(t,s),this.off=(t,s)=>this.events.off(t,s),this.removeListener=(t,s)=>this.events.removeListener(t,s),this.connect=async t=>{try{return await this.engine.connect(t)}catch(s){throw this.logger.error(s.message),s}},this.pair=async t=>{try{return await this.engine.pair(t)}catch(s){throw this.logger.error(s.message),s}},this.approve=async t=>{try{return await this.engine.approve(t)}catch(s){throw this.logger.error(s.message),s}},this.reject=async t=>{try{return await this.engine.reject(t)}catch(s){throw this.logger.error(s.message),s}},this.update=async t=>{try{return await this.engine.update(t)}catch(s){throw this.logger.error(s.message),s}},this.extend=async t=>{try{return await this.engine.extend(t)}catch(s){throw this.logger.error(s.message),s}},this.request=async t=>{try{return await this.engine.request(t)}catch(s){throw this.logger.error(s.message),s}},this.respond=async t=>{try{return await this.engine.respond(t)}catch(s){throw this.logger.error(s.message),s}},this.ping=async t=>{try{return await this.engine.ping(t)}catch(s){throw this.logger.error(s.message),s}},this.emit=async t=>{try{return await this.engine.emit(t)}catch(s){throw this.logger.error(s.message),s}},this.disconnect=async t=>{try{return await this.engine.disconnect(t)}catch(s){throw this.logger.error(s.message),s}},this.find=t=>{try{return this.engine.find(t)}catch(s){throw this.logger.error(s.message),s}},this.name=i?.name||$.name,this.metadata=i?.metadata||Ke();const e=typeof i?.logger<"u"&&typeof i?.logger!="string"?i.logger:Ue(we({level:i?.logger||$.logger}));this.core=i?.core||new me(i),this.logger=k(e,this.name),this.pairing=new lt(this.core,this.logger),this.session=new dt(this.core,this.logger),this.proposal=new pt(this.core,this.logger),this.history=new ht(this.core,this.logger),this.expirer=new ct(this.core,this.logger),this.engine=new at(this)}static async init(i){const e=new z(i);return await e.initialize(),e}get context(){return j(this.logger)}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.pairing.init(),await this.session.init(),await this.proposal.init(),await this.history.init(),await this.expirer.init(),await this.engine.init(),this.logger.info("SignClient Initilization Success")}catch(i){throw this.logger.info("SignClient Initilization Failure"),this.logger.error(i.message),i}}}const gt=z;export{le as ENGINE_CONTEXT,G as ENGINE_RPC_OPTS,se as EXPIRER_CONTEXT,et as EXPIRER_DEFAULT_TTL,m as EXPIRER_EVENTS,ie as EXPIRER_STORAGE_VERSION,re as HISTORY_CONTEXT,_ as HISTORY_EVENTS,ne as HISTORY_STORAGE_VERSION,oe as PAIRING_CONTEXT,tt as PAIRING_DEFAULT_TTL,ae as PROPOSAL_CONTEXT,F as PROPOSAL_EXPIRY,ce as SESSION_CONTEXT,he as SESSION_DEFAULT_TTL,L as SESSION_EXPIRY,H as SIGN_CLIENT_CONTEXT,$ as SIGN_CLIENT_DEFAULT,Be as SIGN_CLIENT_EVENTS,Y as SIGN_CLIENT_PROTOCOL,Qe as SIGN_CLIENT_STORAGE_OPTIONS,T as SIGN_CLIENT_STORAGE_PREFIX,X as SIGN_CLIENT_VERSION,gt as SignClient,z as default};
//# sourceMappingURL=index.es.js.map
{
"name": "@walletconnect/sign-client",
"description": "Sign Client for WalletConnect Protocol",
"version": "2.0.0-rc.1",
"version": "2.0.0-rc.2",
"author": "WalletConnect, Inc. <walletconnect.com>",

@@ -36,3 +36,3 @@ "homepage": "https://github.com/walletconnect/walletconnect-monorepo/",

"dependencies": {
"@walletconnect/core": "^2.0.0-rc.1",
"@walletconnect/core": "2.0.0-rc.2",
"@walletconnect/events": "1.0.0",

@@ -44,4 +44,4 @@ "@walletconnect/heartbeat": "1.0.0",

"@walletconnect/time": "1.0.1",
"@walletconnect/types": "^2.0.0-rc.1",
"@walletconnect/utils": "^2.0.0-rc.1",
"@walletconnect/types": "2.0.0-rc.2",
"@walletconnect/utils": "2.0.0-rc.2",
"pino": "6.7.0",

@@ -51,7 +51,7 @@ "pino-pretty": "4.3.0"

"devDependencies": {
"@walletconnect/jsonrpc-ws-connection": "1.0.2",
"@walletconnect/relay-api": "1.0.5",
"aws-sdk": "^2.1169.0",
"@walletconnect/jsonrpc-ws-connection": "1.0.3",
"@walletconnect/relay-api": "1.0.6",
"aws-sdk": "2.1194.0",
"better-sqlite3": "7.6.2"
}
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc