Web3 Endpoint Cycling
/
70
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 :)