/
JsonRpcProvider.js
74 lines (59 loc) · 1.89 KB
/
JsonRpcProvider.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import axios from 'axios'
import JSONBigInt from 'json-bigint'
import { get, has } from 'lodash'
import Provider from '@liquality/provider'
import Debug from '@liquality/debug'
import { NodeError, RpcError } from '@liquality/errors'
import { version } from '../package.json'
const debug = Debug('jsonrpc')
const { parse } = JSONBigInt({ storeAsString: true, strict: true })
export default class JsonRpcProvider extends Provider {
constructor (uri, username, password) {
super()
this._uri = uri
this._axios = axios.create({
baseURL: uri,
responseType: 'text',
transformResponse: undefined, // https://github.com/axios/axios/issues/907,
validateStatus: (status) => true
})
if (username || password) {
this._axios.defaults.auth = { username, password }
}
}
_prepareRequest (method, params) {
const id = Date.now()
const req = { id, method, params }
debug('jsonrpc request', req)
return req
}
_parseResponse ({ data, status, statusText, headers }) {
if (headers['content-type'] !== 'application/json') {
throw new RpcError(status, statusText, { data })
}
data = parse(data)
debug('parsed jsonrpc response', data)
if (data.error != null) {
throw new RpcError(
get(data, 'error.code', -32603),
get(data, 'error.message', 'An error occurred while processing the RPC call')
)
}
if (!has(data, 'result')) {
throw new RpcError(-32700, 'Missing `result` on the RPC call result')
}
return data.result
}
jsonrpc (method, ...params) {
return this._axios.post(
'',
this._prepareRequest(method, params)
)
.then(this._parseResponse)
.catch(e => {
const { name, message, ...errorNoNameNoMessage } = e
throw new NodeError(`${this._uri} - ${e.toString()}`, errorNoNameNoMessage)
})
}
}
JsonRpcProvider.version = version