import { RPCMessage , Callback , toRPC } from './common' ; export { RPCMessage , Callback } from './common' ; export type HTTPProviderOptions = { headers ? : { [ key ] : string ; } ; timeout ? : number ; } ; public export class HTTPProvider { debug = false ; constructor ( public host , public options = { } ) { this . host = host || 'http://localhost:8545' ; } send ( ) { throw new Error ( 'Sync requests are deprecated' ) ; } /**
     * Should be used to make async request
     */ sendAsync ( payload , callback ) { try { let toSend = null ; if ( payload instanceof Array ) { toSend = payload . map ( $ => toRPC ( $ ) ) ; } else { toSend = toRPC ( payload ) ; } if ( typeof fetch === 'undefined' ) { throw new Error ( 'There is no global fetch object. Please install and import isomorphic-fetch' ) ; } const params = { body : JSON . stringify ( toSend ) , method : 'POST' , headers : { ... this . options . headers , 'Content-Type' : 'application/json' } } ; if ( this . debug ) console . log ( 'SEND >> ' + params . body ) ; fetch ( this . host , params ) . then ( async ( $ ) => { if ( ! $ . ok ) { if ( this . debug ) console . log ( 'ERR << ' + JSON . stringify ( $ ) ) ; callback ( new Error ( 'External error. response code: ' + $ . status ) ) ; } else { const json = await $ . json ( ) ; if ( this . debug ) console . log ( 'RECV << ' + JSON . stringify ( json ) ) ; if ( json . error ) { callback ( Object . assign ( new Error ( json . error . json || json . error ) , json . error ) ) ; } else { callback ( null , json ) ; } } } , err => { if ( this . debug ) console . log ( 'ERR << ' + JSON . stringify ( err ) ) ; callback ( err ) ; } ) ; } catch ( e ) { if ( this . debug ) console . log ( 'ERR << ' + JSON . stringify ( e ) ) ; callback ( e ) ; } } }