0

Below are two code snippets. I have created a 'ganache-testing.js' file and running it using node ganache-testing.js command

Web3 = require("web3");

provider = new Web3.providers.HttpProvider("http://localhost:8545");

web3 = new Web3(provider);

getAccounts = async () => {
  console.log("Started");
  const accounts = await web3.eth.getAccounts();
  for (const account of accounts) {
    const balance = await web3.eth.getBalance(account);
    console.log(account, web3.utils.fromWei(balance, "ether"));
  }
};

getAccounts();

//This is the second code
Web3 = require("web3");

provider = new Web3.providers.WebsocketProvider("ws://localhost:8545");

web3 = new Web3(provider);

getAccounts = async () => {
  console.log("Started");
  const accounts = await web3.eth.getAccounts();
  for (const account of accounts) {
    const balance = await web3.eth.getBalance(account);
    console.log(account, web3.utils.fromWei(balance, "ether"));
  }
  console.log("Completed");
};

getAccounts();

Both of the codes gives the same output:

Started
0x90e04CD9df771C31c6a81c406Bb73f871a3FBDD4 100
0x6ACabD5d20f34C19Aec6405c6956279E465FD6D8 100
0xb5068d22eb632da154A9eEC2c1940691b438F1a5 100
0x6252fe1c3e5a1B9A3eF0c0035d18FCa5b6c3f75B 100
0xafe1c27B9BAbc17BEad0F9326F03b36B4E4A2dB3 100
0x769ef23e6a1727469D75b1860E855F6708DD031a 100
0x33C35c3b96c7C3E27d0FFb38aE30ad868A08aB4A 100
0xa17493a84B10C8790A9Eb4E844BdE8154061eb03 100
0x753fa379E54D5f2DE256785F3b530f228C01b52F 100
0x22fd52A35D14AAd6552C540EE0C7663C622Df22a 100
Completed

However the second code does not return from execution back to the command line. Why would this be happening.

0

In contracts with http connections, web sockets must be closed explicitly.

For your convenience, here is a piece of code which handles both types:

function close() {
    if (this.web3.currentProvider.constructor.name == "WebsocketProvider")
        this.web3.currentProvider.connection.close();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.