Web3 Endpoint Cycling

/ 66

If you're not running your own node, using a web3 endpoint cycling method may help keep your app up and running.


This code will loop until isConnected is truthy, cycling through an array of endpoints until it is able to connect to one.

 while (!isConnected) {     endpointsClone = [...endpoints]     await new Promise(async (resolve, reject) => {         try {             while (!isConnected) {                 (endpointsClone.length === 0) && (resolve(false))                 const idx = Math.floor(Math.random() * endpointsClone.length)                 web3endpoint = endpointsClone.slice(idx, idx + 1)[0]                 try {                     await web3.setProvider(web3endpoint)                     await web3.eth.getBlockNumber()                     isConnected = web3.currentProvider.connected                 } catch (err) {                     console.error(err)                 }                 await this.sleep(1000)             }             window.web3 = web3             resolve(true)         } catch(err) {             reject(err)         }     }) }

Some further enhancements could be made like checking ping/connection time for the endpoints. Maybe I'll add that when I'm not inundated with other TODOs :)

Check out the gist here.