Skip to content

Instantly share code, notes, and snippets.

@L422Y
Last active January 4, 2022 17:17
Show Gist options
  • Save L422Y/57d2f8466baa741b3ce5bc000bb66c75 to your computer and use it in GitHub Desktop.
Save L422Y/57d2f8466baa741b3ce5bc000bb66c75 to your computer and use it in GitHub Desktop.
random web3 provider - check if your provider is connected, pick another at random if not and keep trying
let setupProvider = async () => {
const endpoints = [
'https://bsc-dataseed1.defibit.io/',
'https://bsc-dataseed.binance.org/',
'https://bsc-dataseed1.ninicoin.io/',
'https://bsc-dataseed2.defibit.io/',
'https://bsc-dataseed3.defibit.io/',
'https://bsc-dataseed4.defibit.io/',
'https://bsc-dataseed2.ninicoin.io/',
'https://bsc-dataseed3.ninicoin.io/',
'https://bsc-dataseed4.ninicoin.io/',
'https://bsc-dataseed1.binance.org/',
'https://bsc-dataseed2.binance.org/',
'https://bsc-dataseed3.binance.org/',
'https://bsc-dataseed4.binance.org/',
]
let endpointsClone
let isConnected = false
let web3endpoint
let web3 = new Web3()
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)
}
})
}
return web3endpoint
}
console.log('RPC:' (await setupProvider()))
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment