import { Router , MessageRequester , BACKGROUND_PORT , } from "@keplr-wallet/router" ; import { InteractionForegroundHandler , interactionForegroundInit , InteractionForegroundService , InteractionWaitingData , ApproveInteractionMsg , RejectInteractionMsg , } from "@keplr-wallet/background" ; import { action , observable , IObservableArray , makeObservable , flow , toJS , } from "mobx" ; export class InteractionStore implements InteractionForegroundHandler { @ observable . shallow protected datas : Map < string , InteractionWaitingData [ ] > = new Map ( ) ; @ observable . shallow protected events : Map < string , Omit < InteractionWaitingData , "id" | "isInternal" > [ ] > = new Map ( ) ; constructor ( protected readonly router , protected readonly msgRequester ) { makeObservable ( this ) ; const service = new InteractionForegroundService ( this ) ; interactionForegroundInit ( router , service ) ; } getDatas < T = unknown > ( type ) { return toJS ( this . datas . get ( type ) as InteractionWaitingData < T > [ ] ) ?? [ ] ; } getEvents < T = unknown > ( type ) { return ( toJS ( this . events . get ( type ) as Omit < InteractionWaitingData < T > , "id" | "isInternal" > [ ] ) ?? [ ] ) ; } @ action onInteractionDataReceived ( data ) { if ( ! this . datas . has ( data . type ) ) { this . datas . set ( data . type , observable . array ( [ ] , { deep : false , } ) ) ; } this . datas . get ( data . type ) ! . push ( data ) ; } @ action onEventDataReceived ( data ) { if ( ! this . events . has ( data . type ) ) { this . events . set ( data . type , observable . array ( [ ] , { deep : false , } ) ) ; } this . events . get ( data . type ) ! . push ( data ) ; } @ flow * approve ( type , id , result ) { this . removeData ( type , id ) ; yield this . msgRequester . sendMessage ( BACKGROUND_PORT , new ApproveInteractionMsg ( id , result ) ) ; } param id param result @ flow * approveWithoutRemovingData ( id , result ) { yield this . msgRequester . sendMessage ( BACKGROUND_PORT , new ApproveInteractionMsg ( id , result ) ) ; } @ flow * reject ( type , id ) { this . removeData ( type , id ) ; yield this . msgRequester . sendMessage ( BACKGROUND_PORT , new RejectInteractionMsg ( id ) ) ; } @ flow * rejectAll ( type ) { const datas = this . getDatas ( type ) ; for ( const data of datas ) { yield this . reject ( data . type , data . id ) ; } } @ action removeData ( type , id ) { if ( this . datas . has ( type ) ) { const find = this . datas . get ( type ) ! . find ( ( data ) => { return data . id === id ; } ) ; if ( find ) { ( this . datas . get ( type ) as IObservableArray < InteractionWaitingData > ) . remove ( find ) ; } } } @ action clearEvent ( type ) { if ( this . events . has ( type ) && this . events . get ( type ) ! . length > 0 ) { this . events . set ( type , observable . array ( [ ] , { deep : false , } ) ) ; } } }