This repository was archived by the owner on Sep 27, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathweb3.js
More file actions
48 lines (35 loc) · 1.24 KB
/
web3.js
File metadata and controls
48 lines (35 loc) · 1.24 KB
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
const Web3 = require('web3')
const config = require('./config.json')
// This can also be the node module debug https://www.npmjs.com/package/debug
const debug = (...messages) => console.log(...messages)
const web3 = new Web3()
/**
* Refreshes provider instance and attaches even handlers to it
*/
function refreshProvider(web3Obj, providerUrl) {
let retries = 0
function retry(event) {
// Event is always undefined
if (event) {
debug('Web3 provider disconnected or errored.')
retries += 1
if (retries > 5) {
debug(`Max retries of 5 exceeding: ${retries} times tried`)
return setTimeout(refreshProvider, 5000)
}
} else {
debug(`Reconnecting web3 provider ${config.provider}`)
refreshProvider(web3Obj, providerUrl)
}
return null
}
const provider = new Web3.providers.WebsocketProvider(providerUrl)
provider.on('end', () => retry())
provider.on('error', () => retry())
provider.on('connect', () => console.log('Connected'))
web3Obj.setProvider(provider)
debug('New Web3 provider initiated')
return provider
}
refreshProvider(web3, config.provider)
module.exports = web3