import { JsonRpcProvider } from '@ethersproject/providers' ; import { Wallet } from '@ethersproject/wallet' ; export const ethereumMock = ( ) => { let wallet ; let provider ; let chainId ; const initialize = ( privKey , _chainId , jsonRpcUrl ) => { chainId = _chainId ; provider = new JsonRpcProvider ( jsonRpcUrl , chainId ) ; wallet = new Wallet ( privKey , provider ) ; } ; const wrapResult = ( { id , result } ) => ( { id , result , jsonrpc : '2.0' } ) ; const noOp = ( ) => { } ; const enable = ( ) => Promise . resolve ( [ wallet . address ] ) ; const on = noOp ; const removeAllListeners = noOp ; const getResult = async ( method , params ) => { switch ( method ) { case 'eth_accounts' : return [ wallet . address ] ; case 'wallet_getPermissions' : case 'wallet_requestPermissions' : return undefined ; case 'net_version' : return chainId . toString ( ) ; case 'eth_sendTransaction' : { const { gas , from , type , ... rest } = params [ 0 ] ; const result = await wallet . sendTransaction ( { ... rest , type : type !== undefined ? parseInt ( type , 16 ) : undefined , chainId } ) ; return result . hash ; } default : return await provider . send ( method , params ) ; } } ; const sendAsync = ( { method , params , id } , callback ) => { if ( ! provider || ! wallet ) { callback ( 'Mock not initialized' , null ) ; } else { getResult ( method , params ) . then ( ( result ) => callback ( null , wrapResult ( { id , result } ) ) ) ; } } ; return { initialize , enable , sendAsync , on , removeAllListeners } ; } ;