import { Provider } from '@web3-wallets-kit/types' ; const isProduction = process . env . NODE_ENV === 'production' ; export function warning ( message ) { if ( ! isProduction ) { console . warn ( message ) ; } } export function invariant ( condition , message ? ) { if ( ! condition ) { throw new Error ( `Invariant failed${ isProduction || ! message ? '.' : `: ${ message }` }` ) ; } } export type SendingInterface = 'EIP 1193' | 'Old Web3.js' ; export async function getAccount ( provider , sendingInterface ? ) { const { result : account , sendingInterface : nextInterface } = await send < string | null > ( provider , 'eth_accounts' , ( accounts ) => accounts [ 0 ] || null , sendingInterface ) ; return { account , sendingInterface : nextInterface } ; } export async function getChainId ( provider , sendingInterface ? ) { const { result : chainId , sendingInterface : nextInterface } = await send < number > ( provider , 'eth_chainId' , ( id ) => { if ( ! id ) { throw new Error ( 'ChainId is not found' ) ; } return Number ( id ) ; } , sendingInterface ) ; return { chainId , sendingInterface : nextInterface } ; } async function send < T > ( provider , method , convert , sendingInterface ? ) { if ( sendingInterface !== 'Old Web3.js' ) { try { const sendResult = await provider . send ( method ) ; const result = convert ( isJsonRPCResponse ( sendResult ) ? sendResult . result : sendResult ) ; return { result , sendingInterface : 'EIP 1193' } ; } catch { warning ( 'EIP 1193 sending failed, trying to old Web3.js sending interface' ) ; } } const result = await new Promise ( ( resolve , reject ) => { ( provider . sendAsync || provider . send ) . call ( provider , { method } , ( err , sendResult ) => { err && reject ( err ) ; resolve ( convert ( sendResult ?. result ) ) ; } ) ; } ) ; return { result , sendingInterface : 'Old Web3.js' } ; } const isJsonRPCResponse = ( response ) : response is { result : any ; } => { return typeof response === 'object' && 'jsonrpc' in response && 'result' in response ; } ;