forked from MetaMask/web3-provider-engine
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrpc.js
67 lines (56 loc) · 1.77 KB
/
rpc.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
const xhr = process.browser ? require('xhr') : require('request')
const inherits = require('util').inherits
const createPayload = require('../util/create-payload.js')
const Subprovider = require('./subprovider.js')
const JsonRpcError = require('json-rpc-error')
module.exports = RpcSource
inherits(RpcSource, Subprovider)
function RpcSource(opts) {
const self = this
self.rpcUrl = opts.rpcUrl
}
RpcSource.prototype.handleRequest = function(payload, next, end){
const self = this
const targetUrl = self.rpcUrl
// overwrite id to conflict with other concurrent users
let newPayload = createPayload(payload)
xhr({
uri: targetUrl,
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(newPayload),
rejectUnauthorized: false,
timeout: 20000,
}, function(err, res, body) {
if (err) return end(new JsonRpcError.InternalError(err))
// check for error code
switch (res.statusCode) {
case 405:
return end(new JsonRpcError.MethodNotFound())
case 504: // Gateway timeout
return (function(){
let msg = `Gateway timeout. The request took too long to process. `
msg += `This can happen when querying logs over too wide a block range.`
const err = new Error(msg)
return end(new JsonRpcError.InternalError(err))
})()
default:
if (res.statusCode != 200) {
return end(new JsonRpcError.InternalError(res.body))
}
}
// parse response
let data
try {
data = JSON.parse(body)
} catch (err) {
console.error(err.stack)
return end(new JsonRpcError.InternalError(err))
}
if (data.error) return end(data.error)
end(null, data.result)
})
}