Skip to content

Instantly share code, notes, and snippets.

@th3m477
Last active June 13, 2019 21:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save th3m477/a0d34bdaf5aab4db0064890d9bdb6d14 to your computer and use it in GitHub Desktop.
Save th3m477/a0d34bdaf5aab4db0064890d9bdb6d14 to your computer and use it in GitHub Desktop.
Web3.js websocket connection logic
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