@walletconnect/sign-client
Version:
Sign Client for WalletConnect Protocol
1 lines • 65.6 kB
JavaScript
import{RELAYER_EVENTS as Ye,TRANSPORT_TYPES as P,EXPIRER_EVENTS as Nt,PAIRING_EVENTS as Xe,RELAYER_DEFAULT_PROTOCOL as Ot,EVENT_CLIENT_SESSION_TRACES as D,EVENT_CLIENT_SESSION_ERRORS as H,EVENT_CLIENT_AUTHENTICATE_TRACES as z,EVENT_CLIENT_AUTHENTICATE_ERRORS as re,EVENT_CLIENT_PAIRING_ERRORS as bt,EVENT_CLIENT_PAIRING_TRACES as At,VERIFY_SERVER as xt,Store as B,Core as Vt}from"@walletconnect/core";import{pino as Ct,getDefaultLoggerOptions as kt,generateChildLogger as Dt,getLoggerContext as Lt}from"@walletconnect/logger";import{IEngine as Mt,ISignClient as $t}from"@walletconnect/types";import{THIRTY_DAYS as Kt,SEVEN_DAYS as Je,FIVE_MINUTES as b,ONE_DAY as U,ONE_HOUR as Be,ONE_SECOND as We,toMiliseconds as Oe}from"@walletconnect/time";import{getInternalError as g,BASE64URL as ne,BASE64 as de,hashMessage as W,parseExpirerTarget as Ut,isValidString as Y,isExpired as Z,isValidId as Gt,mergeRequiredAndOptionalNamespaces as jt,calcExpiry as A,engineEvent as R,createDelayedPromise as ee,getSdkError as L,getDeepLink as Ft,handleDeeplinkRedirect as Qt,isSessionCompatible as Ht,hashKey as be,parseChainId as Ae,createEncodedRecap as zt,getRecapFromResources as xe,mergeEncodedRecaps as Yt,TYPE_2 as Xt,getLinkModeURL as ue,validateSignedCacao as Ze,getNamespacedDidChainId as et,getDidAddress as tt,getMethodsFromRecap as st,getChainsFromRecap as it,buildNamespacesFromAuth as rt,formatMessage as Jt,MemoryStore as oe,isValidParams as M,isUndefined as X,isValidRelays as Bt,isValidObject as nt,isValidRequiredNamespaces as Wt,isValidNamespaces as Ve,isConformingNamespaces as ot,isValidErrorReason as Zt,isValidRelay as es,isValidController as ts,isValidNamespacesChainId as at,isValidRequest as ss,isValidNamespacesRequest as is,isValidRequestExpiry as rs,isValidResponse as ns,isValidEvent as os,isValidNamespacesEvent as as,getSearchParamFromURL as ct,isTestRun as cs,isReactNative as ls,getSuiDigest as ps,getNearTransactionIdFromSignedTransaction as lt,buildSignedExtrinsicHash as hs,isValidArray as pt,getAlgorandTransactionId as ht,getSignDirectHash as ds,extractSolanaTransactionId as us,TYPE_1 as Ce,populateAppMetadata as gs}from"@walletconnect/utils";import ys,{EventEmitter as ms}from"events";import{isJsonRpcRequest as ws,isJsonRpcResponse as _s,payloadId as G,getBigIntRpcId as ge,isJsonRpcResult as j,isJsonRpcError as F,formatJsonRpcRequest as ye,formatJsonRpcResult as Es,formatJsonRpcError as fs}from"@walletconnect/jsonrpc-utils";const ke="wc",De=2,Le="client",me=`${ke}@${De}:${Le}:`,we={name:Le,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},Ss={session_proposal:"session_proposal",session_update:"session_update",session_extend:"session_extend",session_ping:"session_ping",session_delete:"session_delete",session_expire:"session_expire",session_request:"session_request",session_request_sent:"session_request_sent",session_event:"session_event",proposal_expire:"proposal_expire",session_authenticate:"session_authenticate",session_request_expire:"session_request_expire",session_connect:"session_connect"},Rs={database:":memory:"},Me="WALLETCONNECT_DEEPLINK_CHOICE",vs={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},Is="history",Ts="0.3",dt="proposal",qs=Kt,$e="Proposal expired",ut="session",J=Je,gt="engine",N={wc_sessionPropose:{req:{ttl:b,prompt:!0,tag:1100},res:{ttl:b,prompt:!1,tag:1101},reject:{ttl:b,prompt:!1,tag:1120},autoReject:{ttl:b,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:b,prompt:!1,tag:1102},res:{ttl:b,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:U,prompt:!1,tag:1104},res:{ttl:U,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:U,prompt:!1,tag:1106},res:{ttl:U,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:b,prompt:!0,tag:1108},res:{ttl:b,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:b,prompt:!0,tag:1110},res:{ttl:b,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:U,prompt:!1,tag:1112},res:{ttl:U,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:U,prompt:!1,tag:1114},res:{ttl:U,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:Be,prompt:!0,tag:1116},res:{ttl:Be,prompt:!1,tag:1117},reject:{ttl:b,prompt:!1,tag:1118},autoReject:{ttl:b,prompt:!1,tag:1119}}},_e={min:b,max:Je},$={idle:"IDLE",active:"ACTIVE"},yt={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"},sui_signAndExecuteTransaction:{key:"digest"},sui_signTransaction:{key:""},hedera_signAndExecuteTransaction:{key:"transactionId"},hedera_executeTransaction:{key:"transactionId"},near_signTransaction:{key:""},near_signTransactions:{key:""},tron_signTransaction:{key:"txID"},xrpl_signTransaction:{key:""},xrpl_signTransactionFor:{key:""},algo_signTxn:{key:""},sendTransfer:{key:"txid"},stacks_stxTransfer:{key:"txId"},polkadot_signTransaction:{key:""},cosmos_signDirect:{key:""}},mt="request",wt=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],_t="wc",Ps=1.5,Et="auth",ft="authKeys",St="pairingTopics",Rt="requests",ae=`${_t}@${1.5}:${Et}:`,ce=`${ae}:PUB_KEY`;var Ns=Object.defineProperty,Os=Object.defineProperties,bs=Object.getOwnPropertyDescriptors,vt=Object.getOwnPropertySymbols,As=Object.prototype.hasOwnProperty,xs=Object.prototype.propertyIsEnumerable,Ke=(S,o,t)=>o in S?Ns(S,o,{enumerable:!0,configurable:!0,writable:!0,value:t}):S[o]=t,I=(S,o)=>{for(var t in o||(o={}))As.call(o,t)&&Ke(S,t,o[t]);if(vt)for(var t of vt(o))xs.call(o,t)&&Ke(S,t,o[t]);return S},x=(S,o)=>Os(S,bs(o)),c=(S,o,t)=>Ke(S,typeof o!="symbol"?o+"":o,t);class Vs extends Mt{constructor(o){super(o),c(this,"name",gt),c(this,"events",new ys),c(this,"initialized",!1),c(this,"requestQueue",{state:$.idle,queue:[]}),c(this,"sessionRequestQueue",{state:$.idle,queue:[]}),c(this,"requestQueueDelay",We),c(this,"expectedPairingMethodMap",new Map),c(this,"recentlyDeletedMap",new Map),c(this,"recentlyDeletedLimit",200),c(this,"relayMessageCache",[]),c(this,"pendingSessions",new Map),c(this,"init",async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(N)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},Oe(this.requestQueueDelay)))}),c(this,"connect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const e=x(I({},t),{requiredNamespaces:t.requiredNamespaces||{},optionalNamespaces:t.optionalNamespaces||{}});await this.isValidConnect(e),e.optionalNamespaces=jt(e.requiredNamespaces,e.optionalNamespaces),e.requiredNamespaces={};const{pairingTopic:s,requiredNamespaces:i,optionalNamespaces:r,sessionProperties:n,scopedProperties:a,relays:l}=e;let p=s,h,u=!1;try{if(p){const T=this.client.core.pairing.pairings.get(p);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),u=T.active}}catch(T){throw this.client.logger.error(`connect() -> pairing.get(${p}) failed`),T}if(!p||!u){const{topic:T,uri:K}=await this.client.core.pairing.create();p=T,h=K}if(!p){const{message:T}=g("NO_MATCHING_KEY",`connect() pairing topic: ${p}`);throw new Error(T)}const d=await this.client.core.crypto.generateKeyPair(),w=N.wc_sessionPropose.req.ttl||b,m=A(w),y=x(I(I({requiredNamespaces:i,optionalNamespaces:r,relays:l??[{protocol:Ot}],proposer:{publicKey:d,metadata:this.client.metadata},expiryTimestamp:m,pairingTopic:p},n&&{sessionProperties:n}),a&&{scopedProperties:a}),{id:G()}),E=R("session_connect",y.id),{reject:_,resolve:V,done:C}=ee(w,$e),v=({id:T})=>{T===y.id&&(this.client.events.off("proposal_expire",v),this.pendingSessions.delete(y.id),this.events.emit(E,{error:{message:$e,code:0}}))};return this.client.events.on("proposal_expire",v),this.events.once(E,({error:T,session:K})=>{this.client.events.off("proposal_expire",v),T?_(T):K&&V(K)}),await this.sendRequest({topic:p,method:"wc_sessionPropose",params:y,throwOnFailedPublish:!0,clientRpcId:y.id}),await this.setProposal(y.id,y),{uri:h,approval:C}}),c(this,"pair",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(t)}catch(e){throw this.client.logger.error("pair() failed"),e}}),c(this,"approve",async t=>{var e,s,i;const r=this.client.core.eventClient.createEvent({properties:{topic:(e=t?.id)==null?void 0:e.toString(),trace:[D.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(q){throw r.setError(H.no_internet_connection),q}try{await this.isValidProposalId(t?.id)}catch(q){throw this.client.logger.error(`approve() -> proposal.get(${t?.id}) failed`),r.setError(H.proposal_not_found),q}try{await this.isValidApprove(t)}catch(q){throw this.client.logger.error("approve() -> isValidApprove() failed"),r.setError(H.session_approve_namespace_validation_failure),q}const{id:n,relayProtocol:a,namespaces:l,sessionProperties:p,scopedProperties:h,sessionConfig:u}=t,d=this.client.proposal.get(n);this.client.core.eventClient.deleteEvent({eventId:r.eventId});const{pairingTopic:w,proposer:m,requiredNamespaces:y,optionalNamespaces:E}=d;let _=(s=this.client.core.eventClient)==null?void 0:s.getEvent({topic:w});_||(_=(i=this.client.core.eventClient)==null?void 0:i.createEvent({type:D.session_approve_started,properties:{topic:w,trace:[D.session_approve_started,D.session_namespaces_validation_success]}}));const V=await this.client.core.crypto.generateKeyPair(),C=m.publicKey,v=await this.client.core.crypto.generateSharedKey(V,C),T=I(I(I({relay:{protocol:a??"irn"},namespaces:l,controller:{publicKey:V,metadata:this.client.metadata},expiry:A(J)},p&&{sessionProperties:p}),h&&{scopedProperties:h}),u&&{sessionConfig:u}),K=P.relay;_.addTrace(D.subscribing_session_topic);try{await this.client.core.relayer.subscribe(v,{transportType:K})}catch(q){throw _.setError(H.subscribe_session_topic_failure),q}_.addTrace(D.subscribe_session_topic_success);const fe=x(I({},T),{topic:v,requiredNamespaces:y,optionalNamespaces:E,pairingTopic:w,acknowledged:!1,self:T.controller,peer:{publicKey:m.publicKey,metadata:m.metadata},controller:V,transportType:P.relay});await this.client.session.set(v,fe),_.addTrace(D.store_session);try{_.addTrace(D.publishing_session_settle),await this.sendRequest({topic:v,method:"wc_sessionSettle",params:T,throwOnFailedPublish:!0}).catch(q=>{throw _?.setError(H.session_settle_publish_failure),q}),_.addTrace(D.session_settle_publish_success),_.addTrace(D.publishing_session_approve),await this.sendResult({id:n,topic:w,result:{relay:{protocol:a??"irn"},responderPublicKey:V},throwOnFailedPublish:!0}).catch(q=>{throw _?.setError(H.session_approve_publish_failure),q}),_.addTrace(D.session_approve_publish_success)}catch(q){throw this.client.logger.error(q),this.client.session.delete(v,L("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(v),q}return this.client.core.eventClient.deleteEvent({eventId:_.eventId}),await this.client.core.pairing.updateMetadata({topic:w,metadata:m.metadata}),await this.deleteProposal(n),await this.client.core.pairing.activate({topic:w}),await this.setExpiry(v,A(J)),{topic:v,acknowledged:()=>Promise.resolve(this.client.session.get(v))}}),c(this,"reject",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(t)}catch(r){throw this.client.logger.error("reject() -> isValidReject() failed"),r}const{id:e,reason:s}=t;let i;try{i=this.client.proposal.get(e).pairingTopic}catch(r){throw this.client.logger.error(`reject() -> proposal.get(${e}) failed`),r}i&&await this.sendError({id:e,topic:i,error:s,rpcOpts:N.wc_sessionPropose.reject}),await this.deleteProposal(e)}),c(this,"update",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(t)}catch(h){throw this.client.logger.error("update() -> isValidUpdate() failed"),h}const{topic:e,namespaces:s}=t,{done:i,resolve:r,reject:n}=ee(),a=G(),l=ge().toString(),p=this.client.session.get(e).namespaces;return this.events.once(R("session_update",a),({error:h})=>{h?n(h):r()}),await this.client.session.update(e,{namespaces:s}),await this.sendRequest({topic:e,method:"wc_sessionUpdate",params:{namespaces:s},throwOnFailedPublish:!0,clientRpcId:a,relayRpcId:l}).catch(h=>{this.client.logger.error(h),this.client.session.update(e,{namespaces:p}),n(h)}),{acknowledged:i}}),c(this,"extend",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(t)}catch(a){throw this.client.logger.error("extend() -> isValidExtend() failed"),a}const{topic:e}=t,s=G(),{done:i,resolve:r,reject:n}=ee();return this.events.once(R("session_extend",s),({error:a})=>{a?n(a):r()}),await this.setExpiry(e,A(J)),this.sendRequest({topic:e,method:"wc_sessionExtend",params:{},clientRpcId:s,throwOnFailedPublish:!0}).catch(a=>{n(a)}),{acknowledged:i}}),c(this,"request",async t=>{this.isInitialized();try{await this.isValidRequest(t)}catch(y){throw this.client.logger.error("request() -> isValidRequest() failed"),y}const{chainId:e,request:s,topic:i,expiry:r=N.wc_sessionRequest.req.ttl}=t,n=this.client.session.get(i);n?.transportType===P.relay&&await this.confirmOnlineStateOrThrow();const a=G(),l=ge().toString(),{done:p,resolve:h,reject:u}=ee(r,"Request expired. Please try again.");this.events.once(R("session_request",a),({error:y,result:E})=>{y?u(y):h(E)});const d="wc_sessionRequest",w=this.getAppLinkIfEnabled(n.peer.metadata,n.transportType);if(w)return await this.sendRequest({clientRpcId:a,relayRpcId:l,topic:i,method:d,params:{request:x(I({},s),{expiryTimestamp:A(r)}),chainId:e},expiry:r,throwOnFailedPublish:!0,appLink:w}).catch(y=>u(y)),this.client.events.emit("session_request_sent",{topic:i,request:s,chainId:e,id:a}),await p();const m={request:x(I({},s),{expiryTimestamp:A(r)}),chainId:e};return await Promise.all([new Promise(async y=>{await this.sendRequest({clientRpcId:a,relayRpcId:l,topic:i,method:d,params:m,expiry:r,throwOnFailedPublish:!0,tvf:this.getTVFParams(a,m)}).catch(E=>u(E)),this.client.events.emit("session_request_sent",{topic:i,request:s,chainId:e,id:a}),y()}),new Promise(async y=>{var E;if(!((E=n.sessionConfig)!=null&&E.disableDeepLink)){const _=await Ft(this.client.core.storage,Me);await Qt({id:a,topic:i,wcDeepLink:_})}y()}),p()]).then(y=>y[2])}),c(this,"respond",async t=>{this.isInitialized(),await this.isValidRespond(t);const{topic:e,response:s}=t,{id:i}=s,r=this.client.session.get(e);r.transportType===P.relay&&await this.confirmOnlineStateOrThrow();const n=this.getAppLinkIfEnabled(r.peer.metadata,r.transportType);j(s)?await this.sendResult({id:i,topic:e,result:s.result,throwOnFailedPublish:!0,appLink:n}):F(s)&&await this.sendError({id:i,topic:e,error:s.error,appLink:n}),this.cleanupAfterResponse(t)}),c(this,"ping",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(t)}catch(s){throw this.client.logger.error("ping() -> isValidPing() failed"),s}const{topic:e}=t;if(this.client.session.keys.includes(e)){const s=G(),i=ge().toString(),{done:r,resolve:n,reject:a}=ee();this.events.once(R("session_ping",s),({error:l})=>{l?a(l):n()}),await Promise.all([this.sendRequest({topic:e,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:s,relayRpcId:i}),r()])}else this.client.core.pairing.pairings.keys.includes(e)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:e}))}),c(this,"emit",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(t);const{topic:e,event:s,chainId:i}=t,r=ge().toString(),n=G();await this.sendRequest({topic:e,method:"wc_sessionEvent",params:{event:s,chainId:i},throwOnFailedPublish:!0,relayRpcId:r,clientRpcId:n})}),c(this,"disconnect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(t);const{topic:e}=t;if(this.client.session.keys.includes(e))await this.sendRequest({topic:e,method:"wc_sessionDelete",params:L("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:e,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(e))await this.client.core.pairing.disconnect({topic:e});else{const{message:s}=g("MISMATCHED_TOPIC",`Session or pairing topic not found: ${e}`);throw new Error(s)}}),c(this,"find",t=>(this.isInitialized(),this.client.session.getAll().filter(e=>Ht(e,t)))),c(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),c(this,"authenticate",async(t,e)=>{var s;this.isInitialized(),this.isValidAuthenticate(t);const i=e&&this.client.core.linkModeSupportedApps.includes(e)&&((s=this.client.metadata.redirect)==null?void 0:s.linkMode),r=i?P.link_mode:P.relay;r===P.relay&&await this.confirmOnlineStateOrThrow();const{chains:n,statement:a="",uri:l,domain:p,nonce:h,type:u,exp:d,nbf:w,methods:m=[],expiry:y}=t,E=[...t.resources||[]],{topic:_,uri:V}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:r});this.client.logger.info({message:"Generated new pairing",pairing:{topic:_,uri:V}});const C=await this.client.core.crypto.generateKeyPair(),v=be(C);if(await Promise.all([this.client.auth.authKeys.set(ce,{responseTopic:v,publicKey:C}),this.client.auth.pairingTopics.set(v,{topic:v,pairingTopic:_})]),await this.client.core.relayer.subscribe(v,{transportType:r}),this.client.logger.info(`sending request to new pairing topic: ${_}`),m.length>0){const{namespace:O}=Ae(n[0]);let k=zt(O,"request",m);xe(E)&&(k=Yt(k,E.pop())),E.push(k)}const T=y&&y>N.wc_sessionAuthenticate.req.ttl?y:N.wc_sessionAuthenticate.req.ttl,K={authPayload:{type:u??"caip122",chains:n,statement:a,aud:l,domain:p,version:"1",nonce:h,iat:new Date().toISOString(),exp:d,nbf:w,resources:E},requester:{publicKey:C,metadata:this.client.metadata},expiryTimestamp:A(T)},fe={eip155:{chains:n,methods:[...new Set(["personal_sign",...m])],events:["chainChanged","accountsChanged"]}},q={requiredNamespaces:{},optionalNamespaces:fe,relays:[{protocol:"irn"}],pairingTopic:_,proposer:{publicKey:C,metadata:this.client.metadata},expiryTimestamp:A(N.wc_sessionPropose.req.ttl),id:G()},{done:Tt,resolve:Ge,reject:Se}=ee(T,"Request expired"),te=G(),le=R("session_connect",q.id),Re=R("session_request",te),pe=async({error:O,session:k})=>{this.events.off(Re,ve),O?Se(O):k&&Ge({session:k})},ve=async O=>{var k,je,Fe;if(await this.deletePendingAuthRequest(te,{message:"fulfilled",code:0}),O.error){const ie=L("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return O.error.code===ie.code?void 0:(this.events.off(le,pe),Se(O.error.message))}await this.deleteProposal(q.id),this.events.off(le,pe);const{cacaos:Qe,responder:Q}=O.result,Te=[],He=[];for(const ie of Qe){await Ze({cacao:ie,projectId:this.client.core.projectId})||(this.client.logger.error(ie,"Signature verification failed"),Se(L("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:qe}=ie,Pe=xe(qe.resources),ze=[et(qe.iss)],qt=tt(qe.iss);if(Pe){const Ne=st(Pe),Pt=it(Pe);Te.push(...Ne),ze.push(...Pt)}for(const Ne of ze)He.push(`${Ne}:${qt}`)}const se=await this.client.core.crypto.generateSharedKey(C,Q.publicKey);let he;Te.length>0&&(he={topic:se,acknowledged:!0,self:{publicKey:C,metadata:this.client.metadata},peer:Q,controller:Q.publicKey,expiry:A(J),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:_,namespaces:rt([...new Set(Te)],[...new Set(He)]),transportType:r},await this.client.core.relayer.subscribe(se,{transportType:r}),await this.client.session.set(se,he),_&&await this.client.core.pairing.updateMetadata({topic:_,metadata:Q.metadata}),he=this.client.session.get(se)),(k=this.client.metadata.redirect)!=null&&k.linkMode&&(je=Q.metadata.redirect)!=null&&je.linkMode&&(Fe=Q.metadata.redirect)!=null&&Fe.universal&&e&&(this.client.core.addLinkModeSupportedApp(Q.metadata.redirect.universal),this.client.session.update(se,{transportType:P.link_mode})),Ge({auths:Qe,session:he})};this.events.once(le,pe),this.events.once(Re,ve);let Ie;try{if(i){const O=ye("wc_sessionAuthenticate",K,te);this.client.core.history.set(_,O);const k=await this.client.core.crypto.encode("",O,{type:Xt,encoding:ne});Ie=ue(e,_,k)}else await Promise.all([this.sendRequest({topic:_,method:"wc_sessionAuthenticate",params:K,expiry:t.expiry,throwOnFailedPublish:!0,clientRpcId:te}),this.sendRequest({topic:_,method:"wc_sessionPropose",params:q,expiry:N.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:q.id})])}catch(O){throw this.events.off(le,pe),this.events.off(Re,ve),O}return await this.setProposal(q.id,q),await this.setAuthRequest(te,{request:x(I({},K),{verifyContext:{}}),pairingTopic:_,transportType:r}),{uri:Ie??V,response:Tt}}),c(this,"approveSessionAuthenticate",async t=>{const{id:e,auths:s}=t,i=this.client.core.eventClient.createEvent({properties:{topic:e.toString(),trace:[z.authenticated_session_approve_started]}});try{this.isInitialized()}catch(y){throw i.setError(re.no_internet_connection),y}const r=this.getPendingAuthRequest(e);if(!r)throw i.setError(re.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${e}`);const n=r.transportType||P.relay;n===P.relay&&await this.confirmOnlineStateOrThrow();const a=r.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),p=be(a),h={type:Ce,receiverPublicKey:a,senderPublicKey:l},u=[],d=[];for(const y of s){if(!await Ze({cacao:y,projectId:this.client.core.projectId})){i.setError(re.invalid_cacao);const v=L("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:e,topic:p,error:v,encodeOpts:h}),new Error(v.message)}i.addTrace(z.cacaos_verified);const{p:E}=y,_=xe(E.resources),V=[et(E.iss)],C=tt(E.iss);if(_){const v=st(_),T=it(_);u.push(...v),V.push(...T)}for(const v of V)d.push(`${v}:${C}`)}const w=await this.client.core.crypto.generateSharedKey(l,a);i.addTrace(z.create_authenticated_session_topic);let m;if(u?.length>0){m={topic:w,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:a,metadata:r.requester.metadata},controller:a,expiry:A(J),authentication:s,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:r.pairingTopic,namespaces:rt([...new Set(u)],[...new Set(d)]),transportType:n},i.addTrace(z.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(w,{transportType:n})}catch(y){throw i.setError(re.subscribe_authenticated_session_topic_failure),y}i.addTrace(z.subscribe_authenticated_session_topic_success),await this.client.session.set(w,m),i.addTrace(z.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:r.pairingTopic,metadata:r.requester.metadata})}i.addTrace(z.publishing_authenticated_session_approve);try{await this.sendResult({topic:p,id:e,result:{cacaos:s,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(r.requester.metadata,n)})}catch(y){throw i.setError(re.authenticated_session_approve_publish_failure),y}return await this.client.auth.requests.delete(e,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:r.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:i.eventId}),{session:m}}),c(this,"rejectSessionAuthenticate",async t=>{this.isInitialized();const{id:e,reason:s}=t,i=this.getPendingAuthRequest(e);if(!i)throw new Error(`Could not find pending auth request with id ${e}`);i.transportType===P.relay&&await this.confirmOnlineStateOrThrow();const r=i.requester.publicKey,n=await this.client.core.crypto.generateKeyPair(),a=be(r),l={type:Ce,receiverPublicKey:r,senderPublicKey:n};await this.sendError({id:e,topic:a,error:s,encodeOpts:l,rpcOpts:N.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(i.requester.metadata,i.transportType)}),await this.client.auth.requests.delete(e,{message:"rejected",code:0}),await this.deleteProposal(e)}),c(this,"formatAuthMessage",t=>{this.isInitialized();const{request:e,iss:s}=t;return Jt(e,s)}),c(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const t=this.relayMessageCache.shift();t&&await this.onRelayMessage(t)}catch(t){this.client.logger.error(t)}},50)}),c(this,"cleanupDuplicatePairings",async t=>{if(t.pairingTopic)try{const e=this.client.core.pairing.pairings.get(t.pairingTopic),s=this.client.core.pairing.pairings.getAll().filter(i=>{var r,n;return((r=i.peerMetadata)==null?void 0:r.url)&&((n=i.peerMetadata)==null?void 0:n.url)===t.peer.metadata.url&&i.topic&&i.topic!==e.topic});if(s.length===0)return;this.client.logger.info(`Cleaning up ${s.length} duplicate pairing(s)`),await Promise.all(s.map(i=>this.client.core.pairing.disconnect({topic:i.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(e){this.client.logger.error(e)}}),c(this,"deleteSession",async t=>{var e;const{topic:s,expirerHasDeleted:i=!1,emitEvent:r=!0,id:n=0}=t,{self:a}=this.client.session.get(s);await this.client.core.relayer.unsubscribe(s),await this.client.session.delete(s,L("USER_DISCONNECTED")),this.addToRecentlyDeleted(s,"session"),this.client.core.crypto.keychain.has(a.publicKey)&&await this.client.core.crypto.deleteKeyPair(a.publicKey),this.client.core.crypto.keychain.has(s)&&await this.client.core.crypto.deleteSymKey(s),i||this.client.core.expirer.del(s),this.client.core.storage.removeItem(Me).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===s&&this.deletePendingSessionRequest(l.id,L("USER_DISCONNECTED"))}),s===((e=this.sessionRequestQueue.queue[0])==null?void 0:e.topic)&&(this.sessionRequestQueue.state=$.idle),r&&this.client.events.emit("session_delete",{id:n,topic:s})}),c(this,"deleteProposal",async(t,e)=>{if(e)try{const s=this.client.proposal.get(t),i=this.client.core.eventClient.getEvent({topic:s.pairingTopic});i?.setError(H.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(t,L("USER_DISCONNECTED")),e?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"proposal")}),c(this,"deletePendingSessionRequest",async(t,e,s=!1)=>{await Promise.all([this.client.pendingRequest.delete(t,e),s?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(i=>i.id!==t),s&&(this.sessionRequestQueue.state=$.idle,this.client.events.emit("session_request_expire",{id:t}))}),c(this,"deletePendingAuthRequest",async(t,e,s=!1)=>{await Promise.all([this.client.auth.requests.delete(t,e),s?Promise.resolve():this.client.core.expirer.del(t)])}),c(this,"setExpiry",async(t,e)=>{this.client.session.keys.includes(t)&&(this.client.core.expirer.set(t,e),await this.client.session.update(t,{expiry:e}))}),c(this,"setProposal",async(t,e)=>{this.client.core.expirer.set(t,A(N.wc_sessionPropose.req.ttl)),await this.client.proposal.set(t,e)}),c(this,"setAuthRequest",async(t,e)=>{const{request:s,pairingTopic:i,transportType:r=P.relay}=e;this.client.core.expirer.set(t,s.expiryTimestamp),await this.client.auth.requests.set(t,{authPayload:s.authPayload,requester:s.requester,expiryTimestamp:s.expiryTimestamp,id:t,pairingTopic:i,verifyContext:s.verifyContext,transportType:r})}),c(this,"setPendingSessionRequest",async t=>{const{id:e,topic:s,params:i,verifyContext:r}=t,n=i.request.expiryTimestamp||A(N.wc_sessionRequest.req.ttl);this.client.core.expirer.set(e,n),await this.client.pendingRequest.set(e,{id:e,topic:s,params:i,verifyContext:r})}),c(this,"sendRequest",async t=>{const{topic:e,method:s,params:i,expiry:r,relayRpcId:n,clientRpcId:a,throwOnFailedPublish:l,appLink:p,tvf:h}=t,u=ye(s,i,a);let d;const w=!!p;try{const E=w?ne:de;d=await this.client.core.crypto.encode(e,u,{encoding:E})}catch(E){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${e} failed`),E}let m;if(wt.includes(s)){const E=W(JSON.stringify(u)),_=W(d);m=await this.client.core.verify.register({id:_,decryptedId:E})}const y=N[s].req;if(y.attestation=m,r&&(y.ttl=r),n&&(y.id=n),this.client.core.history.set(e,u),w){const E=ue(p,e,d);await global.Linking.openURL(E,this.client.name)}else{const E=N[s].req;r&&(E.ttl=r),n&&(E.id=n),E.tvf=x(I({},h),{correlationId:u.id}),l?(E.internal=x(I({},E.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(e,d,E)):this.client.core.relayer.publish(e,d,E).catch(_=>this.client.logger.error(_))}return u.id}),c(this,"sendResult",async t=>{const{id:e,topic:s,result:i,throwOnFailedPublish:r,encodeOpts:n,appLink:a}=t,l=Es(e,i);let p;const h=a&&typeof(global==null?void 0:global.Linking)<"u";try{const w=h?ne:de;p=await this.client.core.crypto.encode(s,l,x(I({},n||{}),{encoding:w}))}catch(w){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${s} failed`),w}let u,d;try{u=await this.client.core.history.get(s,e);const w=u.request;try{d=this.getTVFParams(e,w.params,i)}catch(m){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${m?.message}`)}}catch(w){throw this.client.logger.error(`sendResult() -> history.get(${s}, ${e}) failed`),w}if(h){const w=ue(a,s,p);await global.Linking.openURL(w,this.client.name)}else{const w=u.request.method,m=N[w].res;m.tvf=x(I({},d),{correlationId:e}),r?(m.internal=x(I({},m.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,p,m)):this.client.core.relayer.publish(s,p,m).catch(y=>this.client.logger.error(y))}await this.client.core.history.resolve(l)}),c(this,"sendError",async t=>{const{id:e,topic:s,error:i,encodeOpts:r,rpcOpts:n,appLink:a}=t,l=fs(e,i);let p;const h=a&&typeof(global==null?void 0:global.Linking)<"u";try{const d=h?ne:de;p=await this.client.core.crypto.encode(s,l,x(I({},r||{}),{encoding:d}))}catch(d){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${s} failed`),d}let u;try{u=await this.client.core.history.get(s,e)}catch(d){throw this.client.logger.error(`sendError() -> history.get(${s}, ${e}) failed`),d}if(h){const d=ue(a,s,p);await global.Linking.openURL(d,this.client.name)}else{const d=u.request.method,w=n||N[d].res;this.client.core.relayer.publish(s,p,w)}await this.client.core.history.resolve(l)}),c(this,"cleanup",async()=>{const t=[],e=[];this.client.session.getAll().forEach(s=>{let i=!1;Z(s.expiry)&&(i=!0),this.client.core.crypto.keychain.has(s.topic)||(i=!0),i&&t.push(s.topic)}),this.client.proposal.getAll().forEach(s=>{Z(s.expiryTimestamp)&&e.push(s.id)}),await Promise.all([...t.map(s=>this.deleteSession({topic:s})),...e.map(s=>this.deleteProposal(s))])}),c(this,"onProviderMessageEvent",async t=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(t):await this.onRelayMessage(t)}),c(this,"onRelayEventRequest",async t=>{this.requestQueue.queue.push(t),await this.processRequestsQueue()}),c(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===$.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=$.active;const t=this.requestQueue.queue.shift();if(t)try{await this.processRequest(t)}catch(e){this.client.logger.warn(e)}}this.requestQueue.state=$.idle}),c(this,"processRequest",async t=>{const{topic:e,payload:s,attestation:i,transportType:r,encryptedId:n}=t,a=s.method;if(!this.shouldIgnorePairingRequest({topic:e,requestMethod:a}))switch(a){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:e,payload:s,attestation:i,encryptedId:n});case"wc_sessionSettle":return await this.onSessionSettleRequest(e,s);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(e,s);case"wc_sessionExtend":return await this.onSessionExtendRequest(e,s);case"wc_sessionPing":return await this.onSessionPingRequest(e,s);case"wc_sessionDelete":return await this.onSessionDeleteRequest(e,s);case"wc_sessionRequest":return await this.onSessionRequest({topic:e,payload:s,attestation:i,encryptedId:n,transportType:r});case"wc_sessionEvent":return await this.onSessionEventRequest(e,s);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:e,payload:s,attestation:i,encryptedId:n,transportType:r});default:return this.client.logger.info(`Unsupported request method ${a}`)}}),c(this,"onRelayEventResponse",async t=>{const{topic:e,payload:s,transportType:i}=t,r=(await this.client.core.history.get(e,s.id)).request.method;switch(r){case"wc_sessionPropose":return this.onSessionProposeResponse(e,s,i);case"wc_sessionSettle":return this.onSessionSettleResponse(e,s);case"wc_sessionUpdate":return this.onSessionUpdateResponse(e,s);case"wc_sessionExtend":return this.onSessionExtendResponse(e,s);case"wc_sessionPing":return this.onSessionPingResponse(e,s);case"wc_sessionRequest":return this.onSessionRequestResponse(e,s);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(e,s);default:return this.client.logger.info(`Unsupported response method ${r}`)}}),c(this,"onRelayEventUnknownPayload",t=>{const{topic:e}=t,{message:s}=g("MISSING_OR_INVALID",`Decoded payload on topic ${e} is not identifiable as a JSON-RPC request or a response.`);throw new Error(s)}),c(this,"shouldIgnorePairingRequest",t=>{const{topic:e,requestMethod:s}=t,i=this.expectedPairingMethodMap.get(e);return!i||i.includes(s)?!1:!!(i.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),c(this,"onSessionProposeRequest",async t=>{const{topic:e,payload:s,attestation:i,encryptedId:r}=t,{params:n,id:a}=s;try{const l=this.client.core.eventClient.getEvent({topic:e});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l?.setError(bt.proposal_listener_not_found)),this.isValidConnect(I({},s.params));const p=n.expiryTimestamp||A(N.wc_sessionPropose.req.ttl),h=I({id:a,pairingTopic:e,expiryTimestamp:p,attestation:i,encryptedId:r},n);await this.setProposal(a,h);const u=await this.getVerifyContext({attestationId:i,hash:W(JSON.stringify(s)),encryptedId:r,metadata:h.proposer.metadata});l?.addTrace(At.emit_session_proposal),this.client.events.emit("session_proposal",{id:a,params:h,verifyContext:u})}catch(l){await this.sendError({id:a,topic:e,error:l,rpcOpts:N.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),c(this,"onSessionProposeResponse",async(t,e,s)=>{const{id:i}=e;if(j(e)){const{result:r}=e;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:r});const n=this.client.proposal.get(i);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 l=r.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const p=await this.client.core.crypto.generateSharedKey(a,l);this.pendingSessions.set(i,{sessionTopic:p,pairingTopic:t,proposalId:i,publicKey:a});const h=await this.client.core.relayer.subscribe(p,{transportType:s});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:h}),await this.client.core.pairing.activate({topic:t})}else if(F(e)){await this.deleteProposal(i);const r=R("session_connect",i);if(this.events.listenerCount(r)===0)throw new Error(`emitting ${r} without any listeners, 954`);this.events.emit(r,{error:e.error})}}),c(this,"onSessionSettleRequest",async(t,e)=>{const{id:s,params:i}=e;try{this.isValidSessionSettleRequest(i);const{relay:r,controller:n,expiry:a,namespaces:l,sessionProperties:p,scopedProperties:h,sessionConfig:u}=e.params,d=[...this.pendingSessions.values()].find(y=>y.sessionTopic===t);if(!d)return this.client.logger.error(`Pending session not found for topic ${t}`);const w=this.client.proposal.get(d.proposalId),m=x(I(I(I({topic:t,relay:r,expiry:a,namespaces:l,acknowledged:!0,pairingTopic:d.pairingTopic,requiredNamespaces:w.requiredNamespaces,optionalNamespaces:w.optionalNamespaces,controller:n.publicKey,self:{publicKey:d.publicKey,metadata:this.client.metadata},peer:{publicKey:n.publicKey,metadata:n.metadata}},p&&{sessionProperties:p}),h&&{scopedProperties:h}),u&&{sessionConfig:u}),{transportType:P.relay});await this.client.session.set(m.topic,m),await this.setExpiry(m.topic,m.expiry),await this.client.core.pairing.updateMetadata({topic:d.pairingTopic,metadata:m.peer.metadata}),this.client.events.emit("session_connect",{session:m}),this.events.emit(R("session_connect",d.proposalId),{session:m}),this.pendingSessions.delete(d.proposalId),this.deleteProposal(d.proposalId,!1),this.cleanupDuplicatePairings(m),await this.sendResult({id:e.id,topic:t,result:!0})}catch(r){await this.sendError({id:s,topic:t,error:r}),this.client.logger.error(r)}}),c(this,"onSessionSettleResponse",async(t,e)=>{const{id:s}=e;j(e)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit(R("session_approve",s),{})):F(e)&&(await this.client.session.delete(t,L("USER_DISCONNECTED")),this.events.emit(R("session_approve",s),{error:e.error}))}),c(this,"onSessionUpdateRequest",async(t,e)=>{const{params:s,id:i}=e;try{const r=`${t}_session_update`,n=oe.get(r);if(n&&this.isRequestOutOfSync(n,i)){this.client.logger.warn(`Discarding out of sync request - ${i}`),this.sendError({id:i,topic:t,error:L("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(I({topic:t},s));try{oe.set(r,i),await this.client.session.update(t,{namespaces:s.namespaces}),await this.sendResult({id:i,topic:t,result:!0})}catch(a){throw oe.delete(r),a}this.client.events.emit("session_update",{id:i,topic:t,params:s})}catch(r){await this.sendError({id:i,topic:t,error:r}),this.client.logger.error(r)}}),c(this,"isRequestOutOfSync",(t,e)=>e.toString().slice(0,-3)<t.toString().slice(0,-3)),c(this,"onSessionUpdateResponse",(t,e)=>{const{id:s}=e,i=R("session_update",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);j(e)?this.events.emit(R("session_update",s),{}):F(e)&&this.events.emit(R("session_update",s),{error:e.error})}),c(this,"onSessionExtendRequest",async(t,e)=>{const{id:s}=e;try{this.isValidExtend({topic:t}),await this.setExpiry(t,A(J)),await this.sendResult({id:s,topic:t,result:!0}),this.client.events.emit("session_extend",{id:s,topic:t})}catch(i){await this.sendError({id:s,topic:t,error:i}),this.client.logger.error(i)}}),c(this,"onSessionExtendResponse",(t,e)=>{const{id:s}=e,i=R("session_extend",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);j(e)?this.events.emit(R("session_extend",s),{}):F(e)&&this.events.emit(R("session_extend",s),{error:e.error})}),c(this,"onSessionPingRequest",async(t,e)=>{const{id:s}=e;try{this.isValidPing({topic:t}),await this.sendResult({id:s,topic:t,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:s,topic:t})}catch(i){await this.sendError({id:s,topic:t,error:i}),this.client.logger.error(i)}}),c(this,"onSessionPingResponse",(t,e)=>{const{id:s}=e,i=R("session_ping",s);setTimeout(()=>{if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners 2176`);j(e)?this.events.emit(R("session_ping",s),{}):F(e)&&this.events.emit(R("session_ping",s),{error:e.error})},500)}),c(this,"onSessionDeleteRequest",async(t,e)=>{const{id:s}=e;try{this.isValidDisconnect({topic:t,reason:e.params}),Promise.all([new Promise(i=>{this.client.core.relayer.once(Ye.publish,async()=>{i(await this.deleteSession({topic:t,id:s}))})}),this.sendResult({id:s,topic:t,result:!0}),this.cleanupPendingSentRequestsForTopic({topic:t,error:L("USER_DISCONNECTED")})]).catch(i=>this.client.logger.error(i))}catch(i){this.client.logger.error(i)}}),c(this,"onSessionRequest",async t=>{var e,s,i;const{topic:r,payload:n,attestation:a,encryptedId:l,transportType:p}=t,{id:h,params:u}=n;try{await this.isValidRequest(I({topic:r},u));const d=this.client.session.get(r),w=await this.getVerifyContext({attestationId:a,hash:W(JSON.stringify(ye("wc_sessionRequest",u,h))),encryptedId:l,metadata:d.peer.metadata,transportType:p}),m={id:h,topic:r,params:u,verifyContext:w};await this.setPendingSessionRequest(m),p===P.link_mode&&(e=d.peer.metadata.redirect)!=null&&e.universal&&this.client.core.addLinkModeSupportedApp((s=d.peer.metadata.redirect)==null?void 0:s.universal),(i=this.client.signConfig)!=null&&i.disableRequestQueue?this.emitSessionRequest(m):(this.addSessionRequestToSessionRequestQueue(m),this.processSessionRequestQueue())}catch(d){await this.sendError({id:h,topic:r,error:d}),this.client.logger.error(d)}}),c(this,"onSessionRequestResponse",(t,e)=>{const{id:s}=e,i=R("session_request",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);j(e)?this.events.emit(R("session_request",s),{result:e.result}):F(e)&&this.events.emit(R("session_request",s),{error:e.error})}),c(this,"onSessionEventRequest",async(t,e)=>{const{id:s,params:i}=e;try{const r=`${t}_session_event_${i.event.name}`,n=oe.get(r);if(n&&this.isRequestOutOfSync(n,s)){this.client.logger.info(`Discarding out of sync request - ${s}`);return}this.isValidEmit(I({topic:t},i)),this.client.events.emit("session_event",{id:s,topic:t,params:i}),oe.set(r,s)}catch(r){await this.sendError({id:s,topic:t,error:r}),this.client.logger.error(r)}}),c(this,"onSessionAuthenticateResponse",(t,e)=>{const{id:s}=e;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:t,payload:e}),j(e)?this.events.emit(R("session_request",s),{result:e.result}):F(e)&&this.events.emit(R("session_request",s),{error:e.error})}),c(this,"onSessionAuthenticateRequest",async t=>{var e;const{topic:s,payload:i,attestation:r,encryptedId:n,transportType:a}=t;try{const{requester:l,authPayload:p,expiryTimestamp:h}=i.params,u=await this.getVerifyContext({attestationId:r,hash:W(JSON.stringify(i)),encryptedId:n,metadata:l.metadata,transportType:a}),d={requester:l,pairingTopic:s,id:i.id,authPayload:p,verifyContext:u,expiryTimestamp:h};await this.setAuthRequest(i.id,{request:d,pairingTopic:s,transportType:a}),a===P.link_mode&&(e=l.metadata.redirect)!=null&&e.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:s,params:i.params,id:i.id,verifyContext:u})}catch(l){this.client.logger.error(l);const p=i.params.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),u=this.getAppLinkIfEnabled(i.params.requester.metadata,a),d={type:Ce,receiverPublicKey:p,senderPublicKey:h};await this.sendError({id:i.id,topic:s,error:l,encodeOpts:d,rpcOpts:N.wc_sessionAuthenticate.autoReject,appLink:u})}}),c(this,"addSessionRequestToSessionRequestQueue",t=>{this.sessionRequestQueue.queue.push(t)}),c(this,"cleanupAfterResponse",t=>{this.deletePendingSessionRequest(t.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=$.idle,this.processSessionRequestQueue()},Oe(this.requestQueueDelay))}),c(this,"cleanupPendingSentRequestsForTopic",({topic:t,error:e})=>{const s=this.client.core.history.pending;s.length>0&&s.filter(i=>i.topic===t&&i.request.method==="wc_sessionRequest").forEach(i=>{const r=i.request.id,n=R("session_request",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);this.events.emit(R("session_request",i.request.id),{error:e})})}),c(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===$.active){this.client.logger.info("session request queue is already active.");return}const t=this.sessionRequestQueue.queue[0];if(!t){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=$.active,this.emitSessionRequest(t)}catch(e){this.client.logger.error(e)}}),c(this,"emitSessionRequest",t=>{this.client.events.emit("session_request",t)}),c(this,"onPairingCreated",t=>{if(t.methods&&this.expectedPairingMethodMap.set(t.topic,t.methods),t.active)return;const e=this.client.proposal.getAll().find(s=>s.pairingTopic===t.topic);e&&this.onSessionProposeRequest({topic:t.topic,payload:ye("wc_sessionPropose",x(I({},e),{requiredNamespaces:e.requiredNamespaces,optionalNamespaces:e.optionalNamespaces,relays:e.relays,proposer:e.proposer,sessionProperties:e.sessionProperties,scopedProperties:e.scopedProperties}),e.id),attestation:e.attestation,encryptedId:e.encryptedId})}),c(this,"isValidConnect",async t=>{if(!M(t)){const{message:l}=g("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(t)}`);throw new Error(l)}const{pairingTopic:e,requiredNamespaces:s,optionalNamespaces:i,sessionProperties:r,scopedProperties:n,relays:a}=t;if(X(e)||await this.isValidPairingTopic(e),!Bt(a,!0)){const{message:l}=g("MISSING_OR_INVALID",`connect() relays: ${a}`);throw new Error(l)}if(!X(s)&&nt(s)!==0){const l="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(l):this.client.logger.warn(l),this.validateNamespaces(s,"requiredNamespaces")}if(!X(i)&&nt(i)!==0&&this.validateNamespaces(i,"optionalNamespaces"),X(r)||this.validateSessionProps(r,"sessionProperties"),!X(n)){this.validateSessionProps(n,"scopedProperties");const l=Object.keys(s||{}).concat(Object.keys(i||{}));if(!Object.keys(n).every(p=>l.includes(p)))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(n)}, required/optional namespaces: ${JSON.stringify(l)}`)}}),c(this,"validateNamespaces",(t,e)=>{const s=Wt(t,"connect()",e);if(s)throw new Error(s.message)}),c(this,"isValidApprove",async t=>{if(!M(t))throw new Error(g("MISSING_OR_INVALID",`approve() params: ${t}`).message);const{id:e,namespaces:s,relayProtocol:i,sessionProperties:r,scopedProperties:n}=t;this.checkRecentlyDeleted(e),await this.isValidProposalId(e);const a=this.client.proposal.get(e),l=Ve(s,"approve()");if(l)throw new Error(l.message);const p=ot(a.requiredNamespaces,s,"approve()");if(p)throw new Error(p.message);if(!Y(i,!0)){const{message:h}=g("MISSING_OR_INVALID",`approve() relayProtocol: ${i}`);throw new Error(h)}if(X(r)||this.validateSessionProps(r,"sessionProperties"),!X(n)){this.validateSessionProps(n,"scopedProperties");const h=new Set(Object.keys(s));if(!Object.keys(n).every(u=>h.has(u)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(n)}, approved namespaces: ${Array.from(h).join(", ")}`)}}),c(this,"isValidReject",async t=>{if(!M(t)){const{message:i}=g("MISSING_OR_INVALID",`reject() params: ${t}`);throw new Error(i)}const{id:e,reason:s}=t;if(this.checkRecentlyDeleted(e),await this.isValidProposalId(e),!Zt(s)){const{message:i}=g("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(s)}`);throw new Error(i)}}),c(this,"isValidSessionSettleRequest",t=>{if(!M(t)){const{message:l}=g("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${t}`);throw new Error(l)}const{relay:e,controller:s,namespaces:i,expiry:r}=t;if(!es(e)){const{message:l}=g("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const n=ts(s,"onSessionSettleRequest()");if(n)throw new Error(n.message);const a=Ve(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);if(Z(r)){const{message:l}=g("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),c(this,"isValidUpdate",async t=>{if(!M(t)){const{message:a}=g("MISSING_OR_INVALID",`update() params: ${t}`);throw new Error(a)}const{topic:e,namespaces:s}=t;this.checkRecentlyDeleted(e),await this.isValidSessionTopic(e);const i=this.client.session.get(e),r=Ve(s,"update()");if(r)throw new Error(r.message);const n=ot(i.requiredNamespaces,s,"update()");if(n)throw new Error(n.message)}),c(this,"isValidExtend",async t=>{if(!M(t)){const{message:s}=g("MISSING_OR_INVALID",`extend() params: ${t}`);throw new Error(s)}const{topic:e}=t;this.checkRecentlyDeleted(e),await this.isValidSessionTopic(e)}),c(this,"isValidRequest",async t=>{if(!M(t)){const{message:a}=g("MISSING_OR_INVALID",`request() params: ${t}`);throw new Error(a)}const{topic:e,request:s,chainId:i,expiry:r}=t;this.checkRecentlyDeleted(e),await this.isValidSessionTopic(e);const{namespaces:n}=this.client.session.get(e);if(!at(n,i)){const{message:a}=g("MISSING_OR_INVALID",`request() chainId: ${i}`);throw new Error(a)}if(!ss(s)){const{message:a}=g("MISSING_OR_INVALID",`request() ${JSON.stringify(s)}`);throw new Error(a)}if(!is(n,i,s.method)){const{message:a}=g("MISSING_OR_INVALID",`request() method: ${s.method}`);throw new Error(a)}if(r&&!rs(r,_e)){const{message:a}=g("MISSING_OR_INVALID",`request() expiry: ${r}. Expiry must be a number (in seconds) between ${_e.min} and ${_e.max}`);throw new Error(a)}}),c(this,"isValidRespond",async t=>{var e;if(!M(t)){const{message:r}=g("MISSING_OR_INVALID",`respond() params: ${t}`);throw new Error(r)}const{topic:s,response:i}=t;try{await this.isValidSessionTopic(s)}catch(r){throw(e=t?.response)!=null&&e.id&&this.cleanupAfterResponse(t),r}if(!ns(i)){const{message:r}=g("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(i)}`);throw new Error(r)}}),c(this,"isValidPing",async t=>{if(!M(t)){const{message:s}=g("MISSING_OR_INVALID",`ping() params: ${t}`);throw new Error(s)}const{topic:e}=t;await this.isValidSessionOrPairingTopic(e)}),c(this,"isValidEmit",async t=>{if(!M(t)){const{message:n}=g("MISSING_OR_INVALID",`emit() params: ${t}`);throw new Error(n)}const{topic:e,event:s,chainId:i}=t;await this.isValidSessionTopic(e);con