Last active
June 13, 2019 21:20
-
-
Save th3m477/a0d34bdaf5aab4db0064890d9bdb6d14 to your computer and use it in GitHub Desktop.
Web3.js websocket connection logic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const RECONNECT_MILLIS = 2000 | |
class Web3Connection { | |
constructor() { | |
this.connect() | |
} | |
async connect() { | |
const provider = new Web3.providers.WebsocketProvider('...') | |
this.web3 = new Web3(provider) | |
provider.on('error', (error) => { | |
console.error('WS ERROR', error) | |
setTimeout(() => this.connect(), RECONNECT_MILLIS) | |
}) | |
provider.on('end', (ev) => { | |
console.error('WS END', ev.type, ev.code, ev.reason) | |
setTimeout(() => this.connect(), RECONNECT_MILLIS) | |
}) | |
// Handle individual subscriptions | |
if (this.aSubscription) { | |
await this.aSubscription.unsubscribe() | |
this.aSubscription = null | |
} | |
this.aSubscription = this.web3.eth.subscribe('newBlockHeaders', (error) => { | |
if (error) { console.error('WS BLOCKHEADER ERROR', error) } | |
}).on('data', (result) => { | |
console.log('BLOCK', result.number) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment