@walletconnect/sign-client
Version:
Sign Client for WalletConnect Protocol
1 lines • 66.7 kB
JavaScript
import{RELAYER_EVENTS as ze,TRANSPORT_TYPES as q,EXPIRER_EVENTS as Nt,PAIRING_EVENTS as Ye,RELAYER_DEFAULT_PROTOCOL as Ot,EVENT_CLIENT_SESSION_TRACES as K,EVENT_CLIENT_SESSION_ERRORS as ne,EVENT_CLIENT_AUTHENTICATE_TRACES as z,EVENT_CLIENT_AUTHENTICATE_ERRORS as oe,EVENT_CLIENT_PAIRING_ERRORS as bt,EVENT_CLIENT_PAIRING_TRACES as At,VERIFY_SERVER as xt,Store as W,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{LimitedSet as Kt,getInternalError as g,BASE64URL as ae,BASE64 as Y,hashMessage as U,parseExpirerTarget as Ut,isValidString as J,isExpired as Z,isValidId as Gt,mergeRequiredAndOptionalNamespaces as jt,calcExpiry as x,engineEvent as v,createDelayedPromise as ee,getSdkError as D,getDeepLink as Ft,handleDeeplinkRedirect as Qt,isSessionCompatible as Ht,hashKey as Oe,parseChainId as be,createEncodedRecap as zt,getRecapFromResources as Ae,mergeEncodedRecaps as Yt,TYPE_2 as Jt,getLinkModeURL as ge,validateSignedCacao as Je,getNamespacedDidChainId as Xe,getDidAddress as Be,getMethodsFromRecap as We,getChainsFromRecap as Ze,buildNamespacesFromAuth as et,formatMessage as Xt,MemoryStore as ce,isValidParams as L,isUndefined as X,isValidRelays as Bt,isValidObject as tt,isValidRequiredNamespaces as Wt,isValidNamespaces as xe,isConformingNamespaces as st,isValidErrorReason as Zt,isValidRelay as es,isValidController as ts,isValidNamespacesChainId as it,isValidRequest as ss,isValidNamespacesRequest as is,isValidRequestExpiry as rs,isValidResponse as ns,isValidEvent as os,isValidNamespacesEvent as as,getSearchParamFromURL as rt,isTestRun as cs,isReactNative as ls,getSuiDigest as ps,getNearTransactionIdFromSignedTransaction as nt,buildSignedExtrinsicHash as hs,isValidArray as ot,getAlgorandTransactionId as at,getSignDirectHash as ds,extractSolanaTransactionId as us,TYPE_1 as Ve,populateAppMetadata as gs}from"@walletconnect/utils";import ys,{EventEmitter as ws}from"events";import{THIRTY_DAYS as ms,SEVEN_DAYS as ct,FIVE_MINUTES as V,ONE_DAY as G,ONE_HOUR as lt,ONE_SECOND as _s,toMiliseconds as pt}from"@walletconnect/time";import{isJsonRpcRequest as fs,isJsonRpcResponse as Es,payloadId as j,getBigIntRpcId as ye,isJsonRpcResult as F,isJsonRpcError as Q,formatJsonRpcRequest as te,formatJsonRpcResult as ht,formatJsonRpcError as Ss}from"@walletconnect/jsonrpc-utils";const Ce="wc",ke=2,De="client",we=`${Ce}@${ke}:${De}:`,me={name:De,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},Rs={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"},vs={database:":memory:"},Le="WALLETCONNECT_DEEPLINK_CHOICE",Is={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},Ts="history",qs="0.3",dt="proposal",Ps=ms,Me="Proposal expired",ut="session",B=ct,gt="engine",P={wc_sessionPropose:{req:{ttl:V,prompt:!0,tag:1100},res:{ttl:V,prompt:!1,tag:1101},reject:{ttl:V,prompt:!1,tag:1120},autoReject:{ttl:V,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:V,prompt:!1,tag:1102},res:{ttl:V,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:G,prompt:!1,tag:1104},res:{ttl:G,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:G,prompt:!1,tag:1106},res:{ttl:G,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:V,prompt:!0,tag:1108},res:{ttl:V,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:V,prompt:!0,tag:1110},res:{ttl:V,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:G,prompt:!1,tag:1112},res:{ttl:G,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:G,prompt:!1,tag:1114},res:{ttl:G,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:lt,prompt:!0,tag:1116},res:{ttl:lt,prompt:!1,tag:1117},reject:{ttl:V,prompt:!1,tag:1118},autoReject:{ttl:V,prompt:!1,tag:1119}}},_e={min:V,max:ct},M={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:""}},wt="request",mt=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],_t="wc",Ns=1.5,ft="auth",Et="authKeys",St="pairingTopics",Rt="requests",le=`${_t}@${1.5}:${ft}:`,pe=`${le}:PUB_KEY`;var Os=Object.defineProperty,bs=Object.defineProperties,As=Object.getOwnPropertyDescriptors,vt=Object.getOwnPropertySymbols,xs=Object.prototype.hasOwnProperty,Vs=Object.prototype.propertyIsEnumerable,$e=(E,o,t)=>o in E?Os(E,o,{enumerable:!0,configurable:!0,writable:!0,value:t}):E[o]=t,R=(E,o)=>{for(var t in o||(o={}))xs.call(o,t)&&$e(E,t,o[t]);if(vt)for(var t of vt(o))Vs.call(o,t)&&$e(E,t,o[t]);return E},O=(E,o)=>bs(E,As(o)),c=(E,o,t)=>$e(E,typeof o!="symbol"?o+"":o,t);class Cs extends Mt{constructor(o){super(o),c(this,"name",gt),c(this,"events",new ys),c(this,"initialized",!1),c(this,"requestQueue",{state:M.idle,queue:[]}),c(this,"sessionRequestQueue",{state:M.idle,queue:[]}),c(this,"emittedSessionRequests",new Kt({limit:500})),c(this,"requestQueueDelay",_s),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(P)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},pt(this.requestQueueDelay)))}),c(this,"connect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const e=O(R({},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:$}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});p=T,h=$}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(),y=P.wc_sessionPropose.req.ttl||V,w=x(y),m=O(R(R({requiredNamespaces:i,optionalNamespaces:r,relays:l??[{protocol:Ot}],proposer:{publicKey:d,metadata:this.client.metadata},expiryTimestamp:w,pairingTopic:p},n&&{sessionProperties:n}),a&&{scopedProperties:a}),{id:j()}),S=v("session_connect",m.id),{reject:_,resolve:b,done:C}=ee(y,Me),I=({id:T})=>{T===m.id&&(this.client.events.off("proposal_expire",I),this.pendingSessions.delete(m.id),this.events.emit(S,{error:{message:Me,code:0}}))};return this.client.events.on("proposal_expire",I),this.events.once(S,({error:T,session:$})=>{this.client.events.off("proposal_expire",I),T?_(T):$&&b($)}),await this.sendProposeSession({proposal:m,publishOpts:{internal:{throwOnFailedPublish:!0}}}),await this.setProposal(m.id,m),{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:[K.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(N){throw r.setError(ne.no_internet_connection),N}try{await this.isValidProposalId(t?.id)}catch(N){throw this.client.logger.error(`approve() -> proposal.get(${t?.id}) failed`),r.setError(ne.proposal_not_found),N}try{await this.isValidApprove(t)}catch(N){throw this.client.logger.error("approve() -> isValidApprove() failed"),r.setError(ne.session_approve_namespace_validation_failure),N}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:y,proposer:w,requiredNamespaces:m,optionalNamespaces:S}=d;let _=(s=this.client.core.eventClient)==null?void 0:s.getEvent({topic:y});_||(_=(i=this.client.core.eventClient)==null?void 0:i.createEvent({type:K.session_approve_started,properties:{topic:y,trace:[K.session_approve_started,K.session_namespaces_validation_success]}}));const b=await this.client.core.crypto.generateKeyPair(),C=w.publicKey,I=await this.client.core.crypto.generateSharedKey(b,C),T=R(R(R({relay:{protocol:a??"irn"},namespaces:l,controller:{publicKey:b,metadata:this.client.metadata},expiry:x(B)},p&&{sessionProperties:p}),h&&{scopedProperties:h}),u&&{sessionConfig:u}),$=q.relay;_.addTrace(K.subscribing_session_topic);try{await this.client.core.relayer.subscribe(I,{transportType:$,internal:{skipSubscribe:!0}})}catch(N){throw _.setError(ne.subscribe_session_topic_failure),N}_.addTrace(K.subscribe_session_topic_success);const Ee=O(R({},T),{topic:I,requiredNamespaces:m,optionalNamespaces:S,pairingTopic:y,acknowledged:!1,self:T.controller,peer:{publicKey:w.publicKey,metadata:w.metadata},controller:b,transportType:q.relay});await this.client.session.set(I,Ee),_.addTrace(K.store_session);try{await this.sendApproveSession({sessionTopic:I,proposal:d,pairingProposalResponse:{relay:{protocol:a??"irn"},responderPublicKey:b},sessionSettleRequest:T,publishOpts:{internal:{throwOnFailedPublish:!0}}}),_.addTrace(K.session_approve_publish_success)}catch(N){throw this.client.logger.error(N),this.client.session.delete(I,D("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(I),N}return this.client.core.eventClient.deleteEvent({eventId:_.eventId}),await this.client.core.pairing.updateMetadata({topic:y,metadata:w.metadata}),await this.deleteProposal(n),await this.client.core.pairing.activate({topic:y}),await this.setExpiry(I,x(B)),{topic:I,acknowledged:()=>Promise.resolve(this.client.session.get(I))}}),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:P.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=j(),l=ye().toString(),p=this.client.session.get(e).namespaces;return this.events.once(v("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=j(),{done:i,resolve:r,reject:n}=ee();return this.events.once(v("session_extend",s),({error:a})=>{a?n(a):r()}),await this.setExpiry(e,x(B)),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(m){throw this.client.logger.error("request() -> isValidRequest() failed"),m}const{chainId:e,request:s,topic:i,expiry:r=P.wc_sessionRequest.req.ttl}=t,n=this.client.session.get(i);n?.transportType===q.relay&&await this.confirmOnlineStateOrThrow();const a=j(),l=ye().toString(),{done:p,resolve:h,reject:u}=ee(r,"Request expired. Please try again.");this.events.once(v("session_request",a),({error:m,result:S})=>{m?u(m):h(S)});const d="wc_sessionRequest",y=this.getAppLinkIfEnabled(n.peer.metadata,n.transportType);if(y)return await this.sendRequest({clientRpcId:a,relayRpcId:l,topic:i,method:d,params:{request:O(R({},s),{expiryTimestamp:x(r)}),chainId:e},expiry:r,throwOnFailedPublish:!0,appLink:y}).catch(m=>u(m)),this.client.events.emit("session_request_sent",{topic:i,request:s,chainId:e,id:a}),await p();const w={request:O(R({},s),{expiryTimestamp:x(r)}),chainId:e};return await Promise.all([new Promise(async m=>{await this.sendRequest({clientRpcId:a,relayRpcId:l,topic:i,method:d,params:w,expiry:r,throwOnFailedPublish:!0,tvf:this.getTVFParams(a,w)}).catch(S=>u(S)),this.client.events.emit("session_request_sent",{topic:i,request:s,chainId:e,id:a}),m()}),new Promise(async m=>{var S;if(!((S=n.sessionConfig)!=null&&S.disableDeepLink)){const _=await Ft(this.client.core.storage,Le);await Qt({id:a,topic:i,wcDeepLink:_})}m()}),p()]).then(m=>m[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===q.relay&&await this.confirmOnlineStateOrThrow();const n=this.getAppLinkIfEnabled(r.peer.metadata,r.transportType);F(s)?await this.sendResult({id:i,topic:e,result:s.result,throwOnFailedPublish:!0,appLink:n}):Q(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=j(),i=ye().toString(),{done:r,resolve:n,reject:a}=ee();this.events.once(v("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=ye().toString(),n=j();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:D("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?q.link_mode:q.relay;r===q.relay&&await this.confirmOnlineStateOrThrow();const{chains:n,statement:a="",uri:l,domain:p,nonce:h,type:u,exp:d,nbf:y,methods:w=[],expiry:m}=t,S=[...t.resources||[]],{topic:_,uri:b}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:r});this.client.logger.info({message:"Generated new pairing",pairing:{topic:_,uri:b}});const C=await this.client.core.crypto.generateKeyPair(),I=Oe(C);if(await Promise.all([this.client.auth.authKeys.set(pe,{responseTopic:I,publicKey:C}),this.client.auth.pairingTopics.set(I,{topic:I,pairingTopic:_})]),await this.client.core.relayer.subscribe(I,{transportType:r}),this.client.logger.info(`sending request to new pairing topic: ${_}`),w.length>0){const{namespace:A}=be(n[0]);let k=zt(A,"request",w);Ae(S)&&(k=Yt(k,S.pop())),S.push(k)}const T=m&&m>P.wc_sessionAuthenticate.req.ttl?m:P.wc_sessionAuthenticate.req.ttl,$={authPayload:{type:u??"caip122",chains:n,statement:a,aud:l,domain:p,version:"1",nonce:h,iat:new Date().toISOString(),exp:d,nbf:y,resources:S},requester:{publicKey:C,metadata:this.client.metadata},expiryTimestamp:x(T)},Ee={eip155:{chains:n,methods:[...new Set(["personal_sign",...w])],events:["chainChanged","accountsChanged"]}},N={requiredNamespaces:{},optionalNamespaces:Ee,relays:[{protocol:"irn"}],pairingTopic:_,proposer:{publicKey:C,metadata:this.client.metadata},expiryTimestamp:x(P.wc_sessionPropose.req.ttl),id:j()},{done:Tt,resolve:Ue,reject:Se}=ee(T,"Request expired"),se=j(),he=v("session_connect",N.id),Re=v("session_request",se),de=async({error:A,session:k})=>{this.events.off(Re,ve),A?Se(A):k&&Ue({session:k})},ve=async A=>{var k,Ge,je;if(await this.deletePendingAuthRequest(se,{message:"fulfilled",code:0}),A.error){const re=D("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return A.error.code===re.code?void 0:(this.events.off(he,de),Se(A.error.message))}await this.deleteProposal(N.id),this.events.off(he,de);const{cacaos:Fe,responder:H}=A.result,Te=[],Qe=[];for(const re of Fe){await Je({cacao:re,projectId:this.client.core.projectId})||(this.client.logger.error(re,"Signature verification failed"),Se(D("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:qe}=re,Pe=Ae(qe.resources),He=[Xe(qe.iss)],qt=Be(qe.iss);if(Pe){const Ne=We(Pe),Pt=Ze(Pe);Te.push(...Ne),He.push(...Pt)}for(const Ne of He)Qe.push(`${Ne}:${qt}`)}const ie=await this.client.core.crypto.generateSharedKey(C,H.publicKey);let ue;Te.length>0&&(ue={topic:ie,acknowledged:!0,self:{publicKey:C,metadata:this.client.metadata},peer:H,controller:H.publicKey,expiry:x(B),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:_,namespaces:et([...new Set(Te)],[...new Set(Qe)]),transportType:r},await this.client.core.relayer.subscribe(ie,{transportType:r}),await this.client.session.set(ie,ue),_&&await this.client.core.pairing.updateMetadata({topic:_,metadata:H.metadata}),ue=this.client.session.get(ie)),(k=this.client.metadata.redirect)!=null&&k.linkMode&&(Ge=H.metadata.redirect)!=null&&Ge.linkMode&&(je=H.metadata.redirect)!=null&&je.universal&&e&&(this.client.core.addLinkModeSupportedApp(H.metadata.redirect.universal),this.client.session.update(ie,{transportType:q.link_mode})),Ue({auths:Fe,session:ue})};this.events.once(he,de),this.events.once(Re,ve);let Ie;try{if(i){const A=te("wc_sessionAuthenticate",$,se);this.client.core.history.set(_,A);const k=await this.client.core.crypto.encode("",A,{type:Jt,encoding:ae});Ie=ge(e,_,k)}else await Promise.all([this.sendRequest({topic:_,method:"wc_sessionAuthenticate",params:$,expiry:t.expiry,throwOnFailedPublish:!0,clientRpcId:se}),this.sendRequest({topic:_,method:"wc_sessionPropose",params:N,expiry:P.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:N.id})])}catch(A){throw this.events.off(he,de),this.events.off(Re,ve),A}return await this.setProposal(N.id,N),await this.setAuthRequest(se,{request:O(R({},$),{verifyContext:{}}),pairingTopic:_,transportType:r}),{uri:Ie??b,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(m){throw i.setError(oe.no_internet_connection),m}const r=this.getPendingAuthRequest(e);if(!r)throw i.setError(oe.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${e}`);const n=r.transportType||q.relay;n===q.relay&&await this.confirmOnlineStateOrThrow();const a=r.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),p=Oe(a),h={type:Ve,receiverPublicKey:a,senderPublicKey:l},u=[],d=[];for(const m of s){if(!await Je({cacao:m,projectId:this.client.core.projectId})){i.setError(oe.invalid_cacao);const I=D("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:e,topic:p,error:I,encodeOpts:h}),new Error(I.message)}i.addTrace(z.cacaos_verified);const{p:S}=m,_=Ae(S.resources),b=[Xe(S.iss)],C=Be(S.iss);if(_){const I=We(_),T=Ze(_);u.push(...I),b.push(...T)}for(const I of b)d.push(`${I}:${C}`)}const y=await this.client.core.crypto.generateSharedKey(l,a);i.addTrace(z.create_authenticated_session_topic);let w;if(u?.length>0){w={topic:y,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:a,metadata:r.requester.metadata},controller:a,expiry:x(B),authentication:s,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:r.pairingTopic,namespaces:et([...new Set(u)],[...new Set(d)]),transportType:n},i.addTrace(z.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(y,{transportType:n})}catch(m){throw i.setError(oe.subscribe_authenticated_session_topic_failure),m}i.addTrace(z.subscribe_authenticated_session_topic_success),await this.client.session.set(y,w),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(m){throw i.setError(oe.authenticated_session_approve_publish_failure),m}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:w}}),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===q.relay&&await this.confirmOnlineStateOrThrow();const r=i.requester.publicKey,n=await this.client.core.crypto.generateKeyPair(),a=Oe(r),l={type:Ve,receiverPublicKey:r,senderPublicKey:n};await this.sendError({id:e,topic:a,error:s,encodeOpts:l,rpcOpts:P.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 Xt(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,D("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(Le).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===s&&this.deletePendingSessionRequest(l.id,D("USER_DISCONNECTED"))}),s===((e=this.sessionRequestQueue.queue[0])==null?void 0:e.topic)&&(this.sessionRequestQueue.state=M.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(ne.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(t,D("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=M.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,x(P.wc_sessionPropose.req.ttl)),await this.client.proposal.set(t,e)}),c(this,"setAuthRequest",async(t,e)=>{const{request:s,pairingTopic:i,transportType:r=q.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||x(P.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,publishOpts:u={}}=t,d=te(s,i,a);let y;const w=!!p;try{const _=w?ae:Y;y=await this.client.core.crypto.encode(e,d,{encoding:_})}catch(_){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${e} failed`),_}let m;if(mt.includes(s)){const _=U(JSON.stringify(d)),b=U(y);m=await this.client.core.verify.register({id:b,decryptedId:_})}const S=R(R({},P[s].req),u);if(S.attestation=m,r&&(S.ttl=r),n&&(S.id=n),this.client.core.history.set(e,d),w){const _=ge(p,e,y);await global.Linking.openURL(_,this.client.name)}else S.tvf=O(R({},h),{correlationId:d.id}),l?(S.internal=O(R({},S.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(e,y,S)):this.client.core.relayer.publish(e,y,S).catch(_=>this.client.logger.error(_));return d.id}),c(this,"sendProposeSession",async t=>{const{proposal:e,publishOpts:s}=t,i=te("wc_sessionPropose",e,e.id);this.client.core.history.set(e.pairingTopic,i);const r=await this.client.core.crypto.encode(e.pairingTopic,i,{encoding:Y}),n=U(JSON.stringify(i)),a=U(r),l=await this.client.core.verify.register({id:a,decryptedId:n});await this.client.core.relayer.publishCustom({payload:{pairingTopic:e.pairingTopic,sessionProposal:r},opts:O(R({},s),{id:e.id,publishMethod:"wc_proposeSession",attestation:l})})}),c(this,"sendApproveSession",async t=>{const{sessionTopic:e,pairingProposalResponse:s,proposal:i,sessionSettleRequest:r,publishOpts:n}=t,a=ht(i.id,s),l=await this.client.core.crypto.encode(i.pairingTopic,a,{encoding:Y}),p=te("wc_sessionSettle",r,n?.id),h=await this.client.core.crypto.encode(e,p,{encoding:Y});this.client.core.history.set(e,p),await this.client.core.relayer.publishCustom({payload:{sessionTopic:e,pairingTopic:i.pairingTopic,sessionProposalResponse:l,sessionSettlementRequest:h},opts:O(R({},n),{publishMethod:"wc_approveSession"})})}),c(this,"sendResult",async t=>{const{id:e,topic:s,result:i,throwOnFailedPublish:r,encodeOpts:n,appLink:a}=t,l=ht(e,i);let p;const h=a&&typeof(global==null?void 0:global.Linking)<"u";try{const y=h?ae:Y;p=await this.client.core.crypto.encode(s,l,O(R({},n||{}),{encoding:y}))}catch(y){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${s} failed`),y}let u,d;try{u=await this.client.core.history.get(s,e);const y=u.request;try{d=this.getTVFParams(e,y.params,i)}catch(w){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${w?.message}`)}}catch(y){throw this.client.logger.error(`sendResult() -> history.get(${s}, ${e}) failed`),y}if(h){const y=ge(a,s,p);await global.Linking.openURL(y,this.client.name)}else{const y=u.request.method,w=P[y].res;w.tvf=O(R({},d),{correlationId:e}),r?(w.internal=O(R({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,p,w)):this.client.core.relayer.publish(s,p,w).catch(m=>this.client.logger.error(m))}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=Ss(e,i);let p;const h=a&&typeof(global==null?void 0:global.Linking)<"u";try{const d=h?ae:Y;p=await this.client.core.crypto.encode(s,l,O(R({},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=ge(a,s,p);await global.Linking.openURL(d,this.client.name)}else{const d=u.request.method,y=n||P[d].res;this.client.core.relayer.publish(s,p,y)}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===M.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=M.active;const t=this.requestQueue.queue.shift();if(t)try{await this.processRequest(t)}catch(e){this.client.logger.warn(e)}}this.requestQueue.state=M.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(R({},s.params));const p=n.expiryTimestamp||x(P.wc_sessionPropose.req.ttl),h=R({id:a,pairingTopic:e,expiryTimestamp:p,attestation:i,encryptedId:r},n);await this.setProposal(a,h);const u=await this.getVerifyContext({attestationId:i,hash:U(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:P.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),c(this,"onSessionProposeResponse",async(t,e,s)=>{const{id:i}=e;if(F(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(Q(e)){await this.deleteProposal(i);const r=v("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(m=>m.sessionTopic===t);if(!d)return this.client.logger.error(`Pending session not found for topic ${t}`);const y=this.client.proposal.get(d.proposalId),w=O(R(R(R({topic:t,relay:r,expiry:a,namespaces:l,acknowledged:!0,pairingTopic:d.pairingTopic,requiredNamespaces:y.requiredNamespaces,optionalNamespaces:y.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:q.relay});await this.client.session.set(w.topic,w),await this.setExpiry(w.topic,w.expiry),await this.client.core.pairing.updateMetadata({topic:d.pairingTopic,metadata:w.peer.metadata}),this.client.events.emit("session_connect",{session:w}),this.events.emit(v("session_connect",d.proposalId),{session:w}),this.pendingSessions.delete(d.proposalId),this.deleteProposal(d.proposalId,!1),this.cleanupDuplicatePairings(w),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;F(e)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit(v("session_approve",s),{})):Q(e)&&(await this.client.session.delete(t,D("USER_DISCONNECTED")),this.events.emit(v("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=ce.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:D("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(R({topic:t},s));try{ce.set(r,i),await this.client.session.update(t,{namespaces:s.namespaces}),await this.sendResult({id:i,topic:t,result:!0})}catch(a){throw ce.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=v("session_update",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);F(e)?this.events.emit(v("session_update",s),{}):Q(e)&&this.events.emit(v("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,x(B)),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=v("session_extend",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);F(e)?this.events.emit(v("session_extend",s),{}):Q(e)&&this.events.emit(v("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=v("session_ping",s);setTimeout(()=>{if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners 2176`);F(e)?this.events.emit(v("session_ping",s),{}):Q(e)&&this.events.emit(v("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}),await Promise.all([new Promise(i=>{this.client.core.relayer.once(ze.publish,async()=>{i(await this.deleteSession({topic:t,id:s}))})}),this.sendResult({id:s,topic:t,result:!0}),this.cleanupPendingSentRequestsForTopic({topic:t,error:D("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(R({topic:r},u));const d=this.client.session.get(r),y=await this.getVerifyContext({attestationId:a,hash:U(JSON.stringify(te("wc_sessionRequest",u,h))),encryptedId:l,metadata:d.peer.metadata,transportType:p}),w={id:h,topic:r,params:u,verifyContext:y};await this.setPendingSessionRequest(w),p===q.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(w):(this.addSessionRequestToSessionRequestQueue(w),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=v("session_request",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);F(e)?this.events.emit(v("session_request",s),{result:e.result}):Q(e)&&this.events.emit(v("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=ce.get(r);if(n&&this.isRequestOutOfSync(n,s)){this.client.logger.info(`Discarding out of sync request - ${s}`);return}this.isValidEmit(R({topic:t},i)),this.client.events.emit("session_event",{id:s,topic:t,params:i}),ce.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}),F(e)?this.events.emit(v("session_request",s),{result:e.result}):Q(e)&&this.events.emit(v("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:U(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===q.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:Ve,receiverPublicKey:p,senderPublicKey:h};await this.sendError({id:i.id,topic:s,error:l,encodeOpts:d,rpcOpts:P.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=M.idle,this.processSessionRequestQueue()},pt(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=v("session_request",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);this.events.emit(v("session_request",i.request.id),{error:e})})}),c(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===M.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.emitSessionRequest(t)}catch(e){this.client.logger.error(e)}}),c(this,"emitSessionRequest",t=>{if(this.emittedSessionRequests.has(t.id)){this.client.logger.warn({id:t.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${t.id}`);return}this.sessionRequestQueue.state=M.active,this.emittedSessionRequests.add(t.id),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:te("wc_sessionPropose",O(R({},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(!L(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)&&tt(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)&&tt(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.split(":")[0])))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(!L(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=xe(s,"approve()");if(l)throw new Error(l.message);const p=st(a.requiredNamespaces,s,"approve()");if(p)throw new Error(p.message);if(!J(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.split(":")[0])))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(!L(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(!L(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=xe(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(!L(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=xe(s,"update()");if(r)throw new Error(r.message);const n=st(i.requiredNamespaces,s,"update()");if(n)throw new Error(n.message)}),c(this,"isValidExtend",async t=>{if(!L(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(!L(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(!it(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_INV