import { Message , MessageRequester , Result } from "@keplr-wallet/router" ; import { JSONUint8Array } from "@keplr-wallet/router/build/json-uint8-array" ; import EventEmitter from "eventemitter3" ; export class WCMessageRequester implements MessageRequester { constructor ( protected readonly eventEmitter , protected readonly sessionId ) { } static getVirtualSessionURL = ( sessionId ) : string => { return `https://keplr_wc_virtual.${ sessionId }` ; } ; static isVirtualSessionURL = ( url ) : boolean => { return url . startsWith ( "https://keplr_wc_virtual." ) ; } ; static getSessionIdFromVirtualURL = ( url ) : string => { if ( ! WCMessageRequester . isVirtualSessionURL ( url ) ) { throw new Error ( "URL is not for wallet connect" ) ; } return url . replace ( "https://keplr_wc_virtual." , "" ) . replace ( "/" , "" ) ; } ; async sendMessage < M extends Message < unknown > > ( port , msg ) { msg . validateBasic ( ) ; const url = WCMessageRequester . getVirtualSessionURL ( this . sessionId ) ; msg [ "origin" ] = url ; if ( this . eventEmitter . listenerCount ( "message" ) === 0 ) { throw new Error ( "There is no router to send" ) ; } const result = JSONUint8Array . unwrap ( await new Promise ( ( resolve ) => { this . eventEmitter . emit ( "message" , { message : { port , type : msg . type ( ) , msg : JSONUint8Array . wrap ( msg ) , } , sender : { id : "react-native" , url , resolver : resolve , } , } ) ; } ) ) ; if ( ! result ) { throw new Error ( "Null result" ) ; } if ( result . error ) { throw new Error ( result . error ) ; } return result . return ; } }