import { Router , MessageSender , Result , EnvProducer , } from "@keplr-wallet/router" ; import { getKeplrExtensionRouterId } from "../utils" ; export class ExtensionRouter extends Router { constructor ( envProducer ) { super ( envProducer ) ; } listen ( port ) { if ( ! port ) { throw new Error ( "Empty port" ) ; } this . port = port ; browser . runtime . onMessage . addListener ( this . onMessage ) ; } unlisten ( ) { this . port = "" ; browser . runtime . onMessage . removeListener ( this . onMessage ) ; } protected onMessage = ( message , sender ) : Promise < Result > | undefined => { if ( message . port !== this . port ) { return ; } if ( message . msg ?. routerMeta ?. receiverRouterId && message . msg . routerMeta . receiverRouterId !== getKeplrExtensionRouterId ( ) ) { return ; } return this . onMessageHandler ( message , sender ) ; } ; protected async onMessageHandler ( message , sender ) { try { const result = await this . handleMessage ( message , sender ) ; return { return : result , } ; } catch ( e ) { console . log ( `Failed to process msg ${ message . type }: ${ e ?. message || e ?. toString ( ) }` ) ; if ( e ) { return Promise . resolve ( { error : e . message || e . toString ( ) , } ) ; } else { return Promise . resolve ( { error : "Unknown error, and error is null" , } ) ; } } } }