import WalletConnect from '@walletconnect/client' ; import { ITxData , IWalletConnectSession } from '@walletconnect/types' ; import { TAddress } from '@types' ; import { noOp } from '@utils' ; import { IWalletConnectService } from './types' ; const WALLET_CONNECT_BRIDGE_URI = 'https://bridge.walletconnect.org' ; interface EventHandlers { handleInit ( uri ) : void ; handleConnect ( { address , chainId , session } ) : void ; handleError ( error ) : void ; handleReject ( error ) : void ; handleUpdate ( { address , chainId } ) : void ; handleSessionRequest ? ( uri ) : void ; handleDisconnect ( params ) : void ; } export default function WalletConnectService ( { handleInit , handleConnect , handleError , handleReject , handleUpdate , handleDisconnect = noOp } ) { const connector = new WalletConnect ( { bridge : WALLET_CONNECT_BRIDGE_URI } ) ; const getMessage = ( payload ) => ( payload . params ? payload . params [ 0 ] . message : false ) ; const sendTx = async ( tx ) => connector . sendTransaction ( tx ) ; const signMessage = async ( msg , address ) => connector . signPersonalMessage ( [ msg , address ] ) ; const kill = async ( ) => connector . killSession ( ) ; const init = async ( ) => { if ( connector . connected ) await kill ( ) ; connector . createSession ( ) . then ( ( ) => { handleInit ( connector . uri ) ; } ) ; } ; connector . on ( 'connect' , ( error , payload ) => { if ( error ) { return handleError ( error ) ; } const { accounts , chainId } = payload . params [ 0 ] ; handleConnect ( { address : accounts [ 0 ] as TAddress , chainId , session : connector . session } ) ; } ) ; connector . on ( 'session_update' , ( error , payload ) => { if ( error ) { return handleError ( error ) ; } const { accounts , chainId } = payload . params [ 0 ] ; handleUpdate ( { address : accounts [ 0 ] as TAddress , chainId } ) ; } ) ; connector . on ( 'disconnect' , ( error , payload ) => { if ( error ) { return handleError ( error ) ; } if ( handleReject && getMessage ( payload ) === 'Session Rejected' ) { handleReject ( payload . params ) ; } else { handleDisconnect ( payload ) ; } } ) ; return { init , kill , sendTx , signMessage , isConnected : connector . connected } ; }