Skip to content

Instantly share code, notes, and snippets.

@MagRelo
Last active July 3, 2024 11:38
Show Gist options
  • Save MagRelo/c9fe284d9e3ae44b4c941df646d0b7b8 to your computer and use it in GitHub Desktop.
Save MagRelo/c9fe284d9e3ae44b4c941df646d0b7b8 to your computer and use it in GitHub Desktop.
local websocket connection to ganache-cli
const Web3 = require('web3')
// *WRONG*
// const localProviderUrl = 'wss://localhost:8545'
// Result:
//
// connection not open on send()
// Error in subscription wss://localhost:8545
// Error: connection not open
// at WebsocketProvider.send (/Users/*/node_modules/web3-providers-ws/src/index.js:211:18)
// at Timeout._onTimeout (/Users/*/node_modules/web3-providers-ws/src/index.js:196:19)
// at ontimeout (timers.js:482:11)
// at tryOnTimeout (timers.js:317:5)
// at Timer.listOnTimeout (timers.js:277:5)
// *RIGHT* - use http protocol
const localProviderUrl = 'http://localhost:8545'
// local
const localProvider = new Web3.providers.WebsocketProvider(localProviderUrl)
const localWeb3 = new Web3(localProvider)
localWeb3.eth.subscribe('newBlockHeaders', (error, result) => {
if (error){
console.error('Error in subscription', localProviderUrl)
console.error(error)
} else {
console.error('success', localProviderUrl)
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment