import { initializeProvider } from '@metamask/inpage-provider' ; import ObjectMultiplex from '@metamask/object-multiplex' ; import pump from 'pump' ; import MobilePortStream from './MetaMask/MobilePortStream' ; import ReactNativePostMessageStream from './MetaMask/ReactNativePostMessageStream' ; const INPAGE = 'metamask-inpage' ; const CONTENT_SCRIPT = 'metamask-contentscript' ; const PROVIDER = 'metamask-provider' ; export const injectMobile = ( ) => { const metamaskStream = new ReactNativePostMessageStream ( { name : INPAGE , target : CONTENT_SCRIPT } ) ; initializeProvider ( { connectionStream : metamaskStream , shouldSendMetadata : false } ) ; setupProviderStreams ( ) ; } ; /**
 * Setup function called from content script after the DOM is ready.
 */ function setupProviderStreams ( ) { const pageStream = new ReactNativePostMessageStream ( { name : CONTENT_SCRIPT , target : INPAGE } ) ; const appStream = new MobilePortStream ( { name : CONTENT_SCRIPT } ) ; const pageMux = new ObjectMultiplex ( ) ; pageMux . setMaxListeners ( 25 ) ; const appMux = new ObjectMultiplex ( ) ; appMux . setMaxListeners ( 25 ) ; pump ( pageMux , pageStream , pageMux , ( err ) => logStreamDisconnectWarning ( 'MetaMask Inpage Multiplex' , err ) ) ; pump ( appMux , appStream , appMux , ( err ) => { logStreamDisconnectWarning ( 'MetaMask Background Multiplex' , err ) ; notifyProviderOfStreamFailure ( ) ; } ) ; forwardTrafficBetweenMuxes ( PROVIDER , pageMux , appMux ) ; } param { string } channelName param { ObjectMultiplex } muxA param { ObjectMultiplex } muxB function forwardTrafficBetweenMuxes ( channelName , muxA , muxB ) { const channelA = muxA . createStream ( channelName ) ; const channelB = muxB . createStream ( channelName ) ; pump ( channelA , channelB , channelA , ( err ) => logStreamDisconnectWarning ( `MetaMask muxed traffic for channel "${ channelName }" failed.` , err ) ) ; } param { string } remoteLabel param { Error } err function logStreamDisconnectWarning ( remoteLabel , err ) { let warningMsg = `MetamaskContentscript - lost connection to ${ remoteLabel }` ; if ( err ) { warningMsg += `\n${ err . stack }` ; } console . warn ( warningMsg ) ; console . error ( err ) ; } /**
 * This function must ONLY be called in pump destruction/close callbacks.
 * Notifies the inpage context that streams have failed, via window.postMessage.
 * Relies on @metamask/object-multiplex and post-message-stream implementation details.
 */ function notifyProviderOfStreamFailure ( ) { window . postMessage ( { target : INPAGE , data : { name : PROVIDER , data : { jsonrpc : '2.0' , method : 'METAMASK_STREAM_FAILURE' } } } , window . location . origin ) ; }