-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrpc.js
88 lines (77 loc) · 1.88 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import fetch from 'cross-fetch'
const request = async (options) => {
const response = await fetch(options.url, options)
if (response.status >= 200 && response.status < 300) {
return response.json()
} else {
let res
try {
res = await response.json()
} catch (error) {
// ignore
}
const error = new Error((res && res.error) || response.statusText)
error.response = response
throw error
}
}
const POST = (data) => ({
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
})
export const PUBLIC_RPC_URLS = [
'https://rpc.p2pow.online',
'https://rpc.nanoprofile.online',
'https://mynano.ninja/api/node',
'https://nault.nanos.cc/proxy',
'https://proxy.powernode.cc/proxy',
'https://api.nanex.cc',
'https://vault.nanocrawler.cc/api/node-api',
'https://node.somenano.com/proxy',
'https://proxy.nanos.cc/proxy',
'https://www.bitrequest.app:8020/',
'https://rainstorm.city/api'
]
const defaultConfig = {
randomize: true,
urls: PUBLIC_RPC_URLS
}
export default async function rpc(params, config = {}) {
const { url } = config
if (url) {
try {
const options = { url, ...POST(params) }
const res = await request(options)
return res
} catch (error) {
return {
error
}
}
}
const cnf = Object.assign(defaultConfig, config)
const urls = cnf.randomize
? cnf.urls
.map((value) => ({ value, sort: Math.random() }))
.sort((a, b) => a.sort - b.sort)
.map(({ value }) => value)
: cnf.urls
let error
let res
for (let i = 0; i < urls.length; i++) {
try {
const url = urls[i]
const options = { url, ...POST(params) }
res = await request(options)
} catch (err) {
error = err
}
if (res && !res.error) {
return res
}
}
return { error: (res && res.error) || error }
}